{"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önnimann, 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 * 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": "#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": "/**\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": "#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": "// 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’s 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": "#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×1 and 3×1 bricks (horizontal×vertical 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×3 wall is not acceptable due to the running crack shown in red:\n    //\n    // There are eight ways of forming a crack-free 9×3 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 <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": "#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 \"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 → X\n  // p_i → best[i]\n  // v_i → velocity[i]\n  // x_i → 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 ε and\n//        // the value is -ε and the \"periodic bounds\" [0,2π]. Moding will send\n//        // the value to 2π-ε but the \"velocity\" term will now be huge pointing\n//        // all the way from 2π-ε to ε.\n//        //\n//        // Q: Would it be enough to try (all combinations) of ±(UB-LB) before\n//        // computing velocities to \"best\"s? In the example above, instead of\n//        //\n//        //     v += best - p = ε - (2π-ε) = -2π+2ε\n//        //\n//        // you'd use\n//        //\n//        //     v +=  / argmin  |b - p|            \\  - p = (ε+2π)-(2π-ε) = 2ε\n//        //          |                              |\n//        //           \\ b∈{best, best+2π, best-2π} /\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 <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": "#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 <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": "/*\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": "#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": "//---------------------------------------------------------------------------//\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": "//////////////////////////////////////////////////////////////////////////////\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": "/*\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": "// 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": "#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": "// 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": "#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": "//=======================================================================\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": "#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édif, Olivier Tournaire, Didier Boldo\nemail : librjmcmc@ign.fr\n\nThis software is a generic C++ library for stochastic optimization.\n\nThis software is governed by the CeCILL license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the software under the terms of the CeCILL\nlicense as circulated by CEA, CNRS and INRIA at the following URL\n\"http://www.cecill.info\".\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided only\nwith a limited warranty and the software's author, the holder of the\neconomic rights, and the successive licensors have only limited liability.\n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading, using, modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean that it is complicated to manipulate, and that also\ntherefore means that it is reserved for developers and experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test the software's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or\ndata to be ensured and, more generally, to use and operate it in the\nsame conditions as regards security.\n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL license and that you accept its terms.\n\n***********************************************************************/\n\n#ifndef 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": "/*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 – 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 – 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": "#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": "/*SLAMBOOK2里面，使用智能指针实现G2O的版本*/\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// 曲线模型的顶点，模板参数：优化变量维度和数据类型\nclass CurveFittingVertex : public g2o::BaseVertex<3, Eigen::Vector3d> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  // 重置\n  virtual void setToOriginImpl() override {\n    _estimate << 0, 0, 0;\n  }\n\n  // 更新\n  virtual void oplusImpl(const double *update) override {\n    _estimate += Eigen::Vector3d(update);\n  }\n\n  // 存盘和读盘：留空\n  virtual bool read(istream &in) {}\n\n  virtual bool write(ostream &out) const {}\n};\n\n// 误差模型 模板参数：观测值维度，类型，连接顶点类型\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  // 计算曲线模型误差\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  // 计算雅可比矩阵\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 值， y 值为 _measurement\n};\n\nint main(int argc, char **argv) {\n  double ar = 1.0, br = 2.0, cr = 1.0;         // 真实参数值\n  double ae = 2.0, be = -1.0, ce = 5.0;        // 估计参数值\n  int N = 100;                                 // 数据点\n  double w_sigma = 1.0;                        // 噪声Sigma值\n  double inv_sigma = 1.0 / w_sigma;\n  cv::RNG rng;                                 // OpenCV随机数产生器\n\n  vector<double> x_data, y_data;      // 数据\n  for (int i = 0; i < N; i++) {\n    double x = i / 100.0;\n    x_data.push_back(x);\n    y_data.push_back(exp(ar * x * x + br * x + cr) + rng.gaussian(w_sigma * w_sigma));\n  }\n\n  // 构建图优化，先设定g2o\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<3, 1>> BlockSolverType;  // 每个误差项优化变量维度为3，误差值维度为1\n  typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType; // 线性求解器类型\n\n  // 梯度下降方法，可以从GN, LM, DogLeg 中选\n  auto solver = new g2o::OptimizationAlgorithmGaussNewton(\n    g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));\n  g2o::SparseOptimizer optimizer;     // 图模型\n  optimizer.setAlgorithm(solver);   // 设置求解器\n  optimizer.setVerbose(true);       // 打开调试输出\n\n  // 往图中增加顶点\n  CurveFittingVertex *v = new CurveFittingVertex();\n  v->setEstimate(Eigen::Vector3d(ae, be, ce));\n  v->setId(0);\n  optimizer.addVertex(v);\n\n  // 往图中增加边\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);                // 设置连接的顶点\n    edge->setMeasurement(y_data[i]);      // 观测数值\n    edge->setInformation(Eigen::Matrix<double, 1, 1>::Identity() * 1 / (w_sigma * w_sigma)); // 信息矩阵：协方差矩阵之逆\n    optimizer.addEdge(edge);\n  }\n\n  // 执行优化\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  // 输出优化值\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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#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": "/* -*- 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": "/** @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 <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": "/* -*- 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 \"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": "/**\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": "#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": "// 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": "#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": "// 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": "/*\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": "/**\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": "/* ---------------------------------------------------------------------\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": "#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": "#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// 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": "/*\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": "/*\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": "/*\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": "/*\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": "#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": "/*    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": "#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) 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": "//////////////////////////////////////////////////////////////////////////////\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 © 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": "// \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": "/*\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": "/***************************************************************************\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": "#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": "#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": "//=======================================================================\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": "/** 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": "#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": "/*  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": "#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": "/*\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": "#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": "/*\n * 这是 TJU Robomasters 上位机源码，未经管理层允许严禁传播给其他人（包括队内以及队外）\n *\n * 该文件包含各种预测模型，并封装到了以抽象类Predictor类为基类的类中\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    // 添加一个轨迹点，该函数应该能够自主甄别轨迹点是否与之前追踪的目标一样，如果不是\n    // 预测器自动清空历史数据重新开始预测\n    virtual void AddPredictPoint(PredictionPathPoint ppp) = 0;\n\n    // 预测一段时间之后目标的位置\n    virtual void Predict(double prdTime) = 0;\n    \n    // 主动清除历史记录\n    virtual void ClearHistory() = 0;\n};\n// 线性预测器，由历史数据给出线性的预测（假设目标匀速直线运动）\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        //将视觉根据图像计算出的装甲板在相机坐标系下的位置传给预测类中的worldposition \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        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        //起\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        //按\n        P = F*P*F.t() + Q;\n        //顿\n        Mat S = H*P*H.t() + R; \n        K = P*H.t()*S.inv();\n        //挫\n        Mat y = z - H*x_;\n        x_ = x_ + (K*y);\n        //下笔风雷\n        Mat I = Mat::eye(6,6,CV_32FC1);\n        P = (I - K*H)*P;\n    }\nprotected:\n    float p_tx_old;                  //位置保留量\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        //起\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        //起\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        //按\n        P = F*P*F.t() + Q;\n        //顿\n        Mat S = H*P*H.t() + R; \n        K = P*H.t()*S.inv();\n        //挫\n        Mat y = z - H*x_;\n        x_ = x_ + (K*y);\n        //下笔风雷\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;//发射速度 单位;米/秒\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>> {//数据类型要以Eigen::Matrix给出,因为需要转置操作\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的类型即为继承模板时传入的类型\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//此处误差的定义影响后续解析求导时Jacob矩阵前边是否添加负号\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//需要提供负梯度,与Ceres相同\n\t\t//之所以是负梯度,因为err = _measurement - f(_estimate)\n\t\t//因此为负的\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// 构建图优化，先设定g2o\n\ttypedef g2o::BlockSolver< g2o::BlockSolverTraits<1,1> > Block;  // 每个误差项优化变量维度为3，误差值维度为1\n\tBlock::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>(); // 线性方程求解器\n\tBlock* solver_ptr = new Block( linearSolver );      // 矩阵块求解器\n\t// 梯度下降方法，从GN, LM, DogLeg 中选\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;     // 图模型\n\toptimizer.setAlgorithm( solver );   // 设置求解器\n\toptimizer.setVerbose( true );       // 打开调试输出\n\n\t// 往图中增加顶点\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//加边\n\thello_edge* edge = new hello_edge;\n\tedge->setId(0);\n\tedge->setVertex( 0, v );                // 设置连接的顶点\n\tedge->setMeasurement(66.6);      // 观测数值\n\tedge->setInformation(Eigen::Matrix<double,1,1>::Identity()*0.25); // 信息矩阵：协方差矩阵之逆\n\toptimizer.addEdge( edge );\n\n\t// 执行优化\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// 输出优化值\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": "// 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": "#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é-Ribalta, A., González, 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í 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 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áginas 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án 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úsqueda 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ón 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": "// 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": "// 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": "#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": "//==================================================================================================\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//  (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": "// 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": "// 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": "/** \\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": "#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   × @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 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": "// 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": "/*\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": "#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": "/**\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": "#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úmero de límites 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ón 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ón 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ón 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álculo 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ón\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": "/** \\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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#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": "\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": "#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": "/**\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 © 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#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": "#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": "﻿/*\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": "#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 \"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のキーのペア (i, j) は順番が i < j となっていなければならない。\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の添字と頂点の名前との対応表を作成。\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の定数と変数を初期化。\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// 行列 (-J_{x, y})_{x, y} の最大固有値を計算する。\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>();  // 実質起こらないが、符号関数に渡しているため、スピンが0になる場合がある。\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>();  // 実質起こらないが、符号関数に渡しているため、スピンが0になる場合がある。\r\n\t};\r\n\r\n\t// 温度を下げなければ ``annealing'' ではないが、論文では区別していないので、ここでもこの名称を用いる。\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>();  // 実質起こらないが、符号関数に渡しているため、スピンが0になる場合がある。\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>();  // 実質起こらないが、符号関数に渡しているため、スピンが0になる場合がある。\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": "#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": "#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": "#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数量n,这n个Vertex存储的数据类型\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 不能忽略\n};\n//e(xi)的维度、类型; vertex的类型\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 不能忽略\n};\n\nint main(int argc, char **argv) {    \n\t// 构建图优化，先设定g2o\n\t//注意维度对应--边--顶点---\n\ttypedef g2o::BlockSolver< g2o::BlockSolverTraits<4,4> > Block;  // int _PoseDim, int _LandmarkDim\n\tBlock::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>(); // 线性方程求解器\n\tBlock* solver_ptr = new Block( linearSolver );      // 矩阵块求解器\n\t// 梯度下降方法，从GN, LM, DogLeg 中选\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;     // 图模型\n\toptimizer.setAlgorithm( solver );   // 设置求解器\n\toptimizer.setVerbose( true );       // 打开调试输出\n\tcout << \"add Vertex\" << endl;\n\t// 往图中增加顶点\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//加边\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 );                // 设置连接的顶点\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);      // 观测数值\n\t\t//这个'4'对应于powell_edge第一个参数\n\t\teg->setInformation(Eigen::Matrix<double,4,4>::Identity()*1/0.25); // 信息矩阵：协方差矩阵之逆\n\t\toptimizer.addEdge( eg );\n\t//}\n\t// 执行优化\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// 输出优化值\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": "/**\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": "//   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": "#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": "#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* 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クラスのVectorインスタンスを引数に2つ取り、それぞれの編集距離(Levenstein距離)を計算します。\n * 返値は引数に渡されるVectorインスタンスの要素数で割られるため、0~1の値を取ります。\n * 値が大きければ距離は離れていて、小さければ距離が近いと言う意味になります。計算量はO((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インスタンスの要素数で割らないため，値は0~無限となるLevenstein距離\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)法の実装\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 © 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": "/*\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 <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": "#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": "// 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": "//\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// 文件路径\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": "/*    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) 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": "// 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": "#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": "#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": "\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 << \" °\\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 * @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": "#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": "\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": "#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 * Copyright 2019 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés\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": "/**\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º 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º 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º 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º 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": "/**\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": "#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 * @brief 視錐台クラス\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": "/*******************************************************************************\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": "#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": "/* +------------------------------------------------------------------------+\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": "\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": "# 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×10^(-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": "//\n//  su2_x.hpp\n//\n//  Created by Evan Owen on 4/3/21.\n//  Copyright © 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": "#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’s method (in\n * function contact_function()).\n */\nconstexpr double lambda_atol = 1e-6;\n\n/**\n * The maximum number of iterations of Brent’s method (in function\n * contact_function()).\n */\nconstexpr size_t max_iter = 25;\n\n/**\n * The total number of iterations of the Newton–Raphson 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ᵀ⋅L = 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 *     ⎡ l[0]    0    0 ⎤\n * L = ⎢ l[1] l[3]    0 ⎥.\n *     ⎣ l[2] l[4] l[5] ⎦\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ᵀ⋅L⋅x = 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$−f(\\lambda)@f$ (the “minus” sign comes\n * from the fact that we seek the maximum of @f$f@f$, or the minimum of\n * @f$−f@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–Raphson 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": "/*!\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´epartement 3MI. Ecole Nationale Sup´erieure 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": "#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": "/*    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ˆmgens; 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≤).\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ˆmgens.\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≤, a≤, 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ˆmgens 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": "//######################################################################\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": "//\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": "/* Copyright © 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": "#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": "#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": "/*\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": "// 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": "#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": "////////////////////////////////////////////////////////////////////////////////////\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": "\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": "#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// β-detected nuclear magnetic resonance (β-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": "//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 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": "// 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 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 * @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": "/**\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": "/* 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": "\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": "#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": "// -*- 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 <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": "#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": "#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": "//------------------------------------------------------------------------------\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": "/*\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": "#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’Analyse et d’Architecture 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": "#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–tang\", 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ölder 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": "#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": "// 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": "//\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": "#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": "/**\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 * 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": "//\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\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// 这个程序是对  step-20  的改编，包括一些来自  step-12  的DG方法的技术。因此，该程序的很大一部分与  step-20  非常相似，我们将不再对这些部分进行评论。只有新的东西才会被详细讨论。\n\n//  @sect3{Include files}  \n\n// 这些include文件以前都用过了。\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// 在这个程序中，我们使用一个张量值的系数。由于它可能具有空间依赖性，我们认为它是一个张量值的函数。下面的include文件提供了提供这种功能的 <code>TensorFunction</code> 类。\n\n#include <deal.II/base/tensor_function.h> \n\n// 此外，我们使用 <code>DiscreteTime</code> 类来执行与时间递增有关的操作。\n\n#include <deal.II/base/discrete_time.h> \n\n// 最后一步和以前所有的程序一样。\n\nnamespace Step21 \n{ \n  using namespace dealii; \n// @sect3{The <code>TwoPhaseFlowProblem</code> class}  \n\n// 这是该程序的主类。它与 step-20 中的类很接近，但增加了一些功能。\n\n//  <ul>  \n// <li>  \n// <code>assemble_rhs_S</code> 集合了饱和度方程的右侧。正如介绍中所解释的，这不能被集成到 <code>assemble_rhs</code> 中，因为它取决于在时间步长的第一部分计算的速度。\n\n//  <li>  \n// <code>get_maximal_velocity</code> 的作用正如其名称所示。这个函数用于计算时间步长。\n\n//  <li>  \n// <code>project_back_saturation</code>  将所有饱和度小于0的自由度重置为0，所有饱和度大于1的自由度重置为1。   </ul>  \n\n// 该类的其余部分应该是非常明显的。变量 <code>viscosity</code> 存储粘度 $\\mu$ ，它进入了非线性方程中的几个公式。变量 <code>time</code> 记录了模拟过程中的时间信息。\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// 目前，压力方程的右侧仅仅是零函数。但是，如果需要的话，程序的其余部分完全可以处理其他的东西。\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// 接下来是压力边界值。正如介绍中提到的，我们选择一个线性压力场。\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// 然后，我们还需要边界的流入部分的边界值。某物是否为流入部分的问题是在组装右手边时决定的，我们只需要提供边界值的功能描述。这正如介绍中所解释的。\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// 最后，我们需要初始数据。实际上，我们只需要饱和度的初始数据，但我们很懒，所以以后在第一个时间步骤之前，我们会简单地从一个包含所有矢量分量的函数中插值出前一个时间步骤的整个解决方案。\n//因此，\n//我们简单地创建一个所有分量都返回0的函数。我们通过简单地将每个函数转发到 Functions::ZeroFunction 类来做到这一点。为什么不在这个程序中我们目前使用 <code>InitialValues</code> 类的地方立即使用呢？因为这样，以后再回去选择不同的函数来做初始值就更简单了。\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// 正如介绍中所宣布的，我们实现了两个不同的渗透率张量场。我们把它们各自放入一个命名空间，这样以后就可以很容易地在代码中用另一个来代替一个。\n\n//  @sect4{Single curving crack permeability}  \n\n// 渗透率的第一个函数是模拟单个弯曲裂缝的函数。它在 step-20 的结尾已经使用过了，它的函数形式在本教程程序的介绍中给出。和以前的一些程序一样，我们必须声明KInverse类的一个（似乎是不必要的）默认构造函数，以避免某些编译器的警告。\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// 这个函数的作用与介绍中公布的一样，即在随机的地方创建一个叠加的指数。对于这个类，有一件事值得考虑。这个问题的核心是，这个类使用随机函数创建指数的中心。如果我们因此在每次创建本类型的对象时都创建中心，我们每次都会得到一个不同的中心列表。这不是我们对这种类型的类的期望：它们应该可靠地表示同一个函数。\n\n// 解决这个问题的方法是使中心列表成为这个类的静态成员变量，也就是说，在整个程序中只存在一个这样的变量，而不是为这个类型的每个对象。这正是我们所要做的。\n\n// 然而，接下来的问题是，我们需要一种方法来初始化这个变量。由于这个变量是在程序开始时初始化的，我们不能使用普通的成员函数来实现，因为当时身边可能没有这个类型的对象。因此C++标准规定，只有非成员函数和静态成员函数可以用来初始化静态变量。我们通过定义一个函数 <code>get_centers</code> 来使用后一种可能性，该函数在调用时计算中心点的列表。\n\n// 注意，这个类在2D和3D中都能正常工作，唯一的区别是我们在3D中使用了更多的点：通过实验我们发现，我们在3D中比2D中需要更多的指数（毕竟我们有更多的地方需要覆盖，如果我们想保持中心之间的距离大致相等），所以我们在2D中选择40，在3D中选择100。对于任何其他维度，该函数目前不知道该怎么做，所以只是抛出一个异常，表明这一点。\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// 还有两个数据我们需要描述，即反流动性函数和饱和度曲线。它们的形式也在介绍中给出。\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// 我们使用的线性求解器也完全类似于  step-20  中使用的。因此，下面的类是逐字逐句从那里复制过来的。请注意，这里的类不仅是从 step-20 中复制的，而且在deal.II中也有重复的类。在这个例子的未来版本中，它们应该被一个有效的方法所取代，不过。有一个变化：如果线性系统的尺寸很小，即当网格很粗时，那么在 <code>src.size()</code> 函数中的求解器收敛之前，设置 <code>vmult()</code> CG迭代的最大值有时是不够的。(当然，这是数值取舍的结果，因为我们知道在纸面上，CG方法最多在 <code>src.size()</code> 步内收敛)。因此，我们将最大的迭代次数设定为等于线性系统的最大规模和200。\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// 现在是主类的实现。它的大部分内容实际上是从  step-20  中复制过来的，所以我们不会对它进行详细的评论。你应该试着先熟悉一下那个程序，然后这里发生的大部分事情就应该很清楚了。\n\n//  @sect4{TwoPhaseFlowProblem::TwoPhaseFlowProblem}  \n\n// 首先是构造函数。我们使用 $RT_k \\times DQ_k \\times DQ_k$ 空间。对于初始化DiscreteTime对象，我们不在构造函数中设置时间步长，因为我们还没有它的值。时间步长最初被设置为零，但在需要增量时间之前，它将被计算出来，正如介绍的一个小节中所描述的。时间对象在内部阻止自己在 $dt = 0$ 时被递增，迫使我们在推进时间之前为 $dt$ 设置一个非零的期望大小。\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// 下一个函数从众所周知的函数调用开始，创建和细化一个网格，然后将自由度与之关联。它所做的事情与 step-20 中的相同，只是现在是三个组件而不是两个。\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// 这是组装线性系统的函数，或者至少是除了(1,3)块之外的所有东西，它取决于在这个时间步长中计算的仍然未知的速度（我们在 <code>assemble_rhs_S</code> 中处理这个问题）。它的大部分内容与 step-20 一样，但这次我们必须处理一些非线性的问题。 然而，该函数的顶部与往常一样（注意我们在开始时将矩阵和右手边设置为零&mdash; 对于静止问题我们不必这样做，因为在那里我们只使用一次矩阵对象，而且在开始时它是空的）。\n\n// 注意，在目前的形式下，该函数使用 RandomMedium::KInverse 类中实现的渗透率。切换到单曲裂缝渗透率函数就像改变命名空间名称一样简单。\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// 这里是第一个重要的区别。我们必须在正交点上获得前一个时间步骤的饱和函数值。为此，我们可以使用 FEValues::get_function_values （之前已经在 step-9 、 step-14 和 step-15 中使用），这个函数接收一个解向量并返回当前单元的正交点的函数值列表。事实上，它返回每个正交点的完整矢量值解，即不仅是饱和度，还有速度和压力。\n\n        fe_values.get_function_values(old_solution, old_solution_values); \n\n// 然后，我们还必须得到压力的右手边和反渗透性张量在正交点的数值。\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// 有了这些，我们现在可以在这个单元格上的所有正交点和形状函数上进行循环，并将我们在这个函数中处理的矩阵和右手边的那些部分组合起来。考虑到引言中所述的双线性形式的明确形式，贡献中的各个条款应该是不言自明的。\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// 接下来，我们还必须处理压力边界值。这一点，还是和 step-20 中一样。\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// 在所有单元的循环中，最后一步是将局部贡献转移到全局矩阵和右侧向量中。\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// 矩阵和右手边的组装就这么多了。请注意，我们不需要插值和应用边界值，因为它们都已经在弱式中被处理过了。\n\n//  @sect4{TwoPhaseFlowProblem::assemble_rhs_S}  \n\n// 正如在介绍中所解释的，我们只有在计算出速度后才能评估饱和方程的右边。因此，我们有这个单独的函数来实现这个目的。\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// 首先是单元格条款。按照介绍中的公式，这些是  $(S^n,\\sigma)-(F(S^n) \\mathbf{v}^{n+1},\\nabla \\sigma)$  ，其中  $\\sigma$  是测试函数的饱和成分。\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// 其次，我们必须处理面的边界上的通量部分。这就有点麻烦了，因为我们首先要确定哪些是细胞边界的流入和流出部分。如果我们有一个流入的边界，我们需要评估面的另一边的饱和度（或者边界值，如果我们在域的边界上）。\n\n// 所有这些都有点棘手，但在  step-9  中已经有了一些详细的解释。请看这里，这应该是如何工作的!\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// 在所有这些准备工作之后，我们最终以与  step-20  相同的方式解决速度和压力的线性系统。在这之后，我们必须处理饱和方程（见下文）。\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// 首先是压力，使用前两个方程的压力舒尔补。\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// 现在是速度。\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// 最后，我们必须处理好饱和度方程。在这里，我们要做的第一件事是使用介绍中的公式来确定时间步长。知道了我们领域的形状，以及我们通过有规律地划分单元来创建网格，我们可以很容易地计算出每个单元的直径（事实上我们使用的是单元坐标方向上的线性扩展，而不是直径）。请注意，我们将在 step-24 中学习一种更通用的方法，在那里我们使用 GridTools::minimal_cell_diameter 函数。\n\n// 我们使用一个辅助函数来计算下面定义的最大速度，有了这些，我们就可以评估我们新的时间步长了。我们使用方法 DiscreteTime::set_desired_next_time_step() 来向DiscreteTime对象建议新的时间步长的计算值。在大多数情况下，时间对象使用精确提供的值来增加时间。在某些情况下，时间对象可以进一步修改步骤大小。例如，如果计算出的时间增量超过了结束时间，它将被相应地截断。\n\n    time.set_desired_next_step_size(std::pow(0.5, double(n_refinement_steps)) / \n                                    get_maximal_velocity()); \n\n// 下一步是组装右手边，然后把所有的东西都传给解。最后，我们把饱和度投射回物理上合理的范围。\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// 这里没有什么值得惊讶的。由于程序会做大量的时间步骤，我们只在每第五个时间步骤创建一个输出文件，并在文件的顶部已经跳过所有其他时间步骤。\n\n// 在为接近函数底部的输出创建文件名时，我们将时间步长的数字转换为字符串表示，用前导零填充到四位数。我们这样做是因为这样所有的输出文件名都有相同的长度，因此在创建目录列表时可以很好地排序。\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// 在这个函数中，我们简单地遍历所有的饱和自由度，并确保如果它们离开了物理上的合理范围，它们将被重置到区间  $[0,1]$  。要做到这一点，我们只需要循环解决向量的所有饱和分量；这些分量存储在块2中（块0是速度，块1是压力）。\n\n// 值得注意的是，当时间步长选择如介绍中提到的那样时，这个函数几乎从未触发过，这一点可能很有启发。然而，如果我们只选择稍大的时间步长，我们会得到大量超出适当范围的数值。严格来说，如果我们选择的时间步长足够小，这个函数因此是不必要的。从某种意义上说，这个函数只是一个安全装置，以避免由于个别自由度在几个时间步长之前变得不符合物理条件而导致我们的整个解决方案变得不符合物理条件的情况。\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// 下面的函数用于确定允许的最大时间步长。它的作用是在域中的所有正交点上循环，找出速度的最大幅度。\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// 这是我们主类的最后一个函数。它的简洁不言自明。只有两点是值得注意的。首先，该函数在开始时将初始值投射到有限元空间上； VectorTools::project 函数这样做需要一个表明悬挂节点约束的参数。我们在这个程序中没有（我们在一个均匀细化的网格上计算），但是这个函数当然需要这个参数。所以我们必须创建一个约束对象。在原始状态下，约束对象是没有排序的，在使用前必须进行排序（使用 AffineConstraints::close 函数）。这就是我们在这里所做的，这也是为什么我们不能简单地用一个匿名的临时对象 <code>AffineConstraints<double>()</code> 作为第二个参数来调用 VectorTools::project 函数。\n\n// 值得一提的第二点是，我们只在求解每个时间步长对应的线性系统的过程中计算当前时间步长。因此，我们只有在时间步长结束时才能输出一个时间步长的当前时间。我们通过调用循环内的方法 DiscreteTime::advance_time() 来增加时间。由于我们在增量后报告时间和dt，我们必须调用方法 DiscreteTime::get_previous_step_size() ，而不是 DiscreteTime::get_next_step_size(). 。 经过许多步，当模拟到达结束时间时，最后的dt由DiscreteTime类选择，其方式是最后一步正好在结束时间完成。\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// 这就是了。在主函数中，我们将有限元空间的度数传递给TwoPhaseFlowProblem对象的构造函数。 这里，我们使用零度元素，即 $RT_0\\times DQ_0 \\times DQ_0$  。其余部分与其他所有程序一样。\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": "#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 <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": "#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": "/*\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 <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": "/** @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 <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": "/*\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é de l'Equation de Schrödinger non relativiste dépendant du temps\n * \n * ## Equation de Schrödinger non relativiste dépendant 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érateur 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é 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éduite**\n\\f[\\hbar \\equiv 6.582119514\\times10^{−22}\\,\\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ées nécessaires pour tracer les grraphes\n *\n *@return la fonction créer des fichier .txt et retourne 0\n */\n\nint main()\n{\n    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 <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": "/* -*- 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": "#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// β-detected nuclear magnetic resonance (β-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 \"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 * Filename    : algorithms.cpp                                                                        *\n * Project     : Planewalker - Schnorr-Euchner sphere decoder simulation for space-time lattice codes  *\n * Authors     : Pasi Pyrrö, 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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#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": "#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 <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": "#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": "#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 \"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": "﻿/*! \\file mabinogi_roulette_mc.cpp\n    \\brief マビノギのルーレットビンゴをモンテカルロ・シミュレーションする\n\n    Copyright © 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        列のサイズ\n    */\n    static auto constexpr COLUMN = 5ULL;\n\n    //! A global variable (constant expression).\n    /*!\n        行のサイズ\n    */\n    static auto constexpr ROW = 5ULL;\n\n    //! A global variable (constant expression).\n    /*!\n        ビンゴボードのマス数\n    */\n    static auto constexpr BOARDSIZE = ROW * COLUMN;\n\n    //! A global variable (constant expression).\n    /*!\n        モンテカルロシミュレーションの試行回数\n    */\n    static auto constexpr MCMAX = 1000000U;\n\n    //! A global variable (constant expression).\n    /*!\n        行・列の総数\n    */\n    static auto constexpr ROWCOLUMN = ROW + COLUMN;\n\n    //! A typedef.\n    /*!\n        そのマスに書かれてある番号と、そのマスが当たったかどうかを示すフラグのstd::pair\n    */\n    using mypair = std::pair<std::int32_t, bool>;\n\n    //! A typedef.\n    /*!\n        数字と数字のstd::pair\n    */\n    using mypair2 = std::pair<std::int32_t, std::int32_t>;\n\n    //! A typedef.\n    /*!\n        (n + 1)個目の行・列が埋まったときの分布を格納するためのmapの型\n    */\n    using mymap = std::map<std::int32_t, std::int32_t>;\n    \n\t//! A function.\n\t/*!\n\t\t(n + 1)個目の行・列またはマスが埋まったときの平均試行回数、埋まっているマスまたは行・列の平均個数を求める\n\t\t\\param mcresult モンテカルロ・シミュレーションの結果が格納された二次元可変長配列\n\t\t\\param size 行・列またはマスの総数\n\t\t\\return (n + 1)個目の行・列が埋まったときの平均試行回数、埋まっているマスの平均個数が格納された可変長配列のstd::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)個目の行・列が埋まったときの中央値を求める\n\t\t\\param (n + 1)個目の数値n\n\t\t\\param mcresult モンテカルロ・シミュレーションの結果が格納された二次元可変長配列\n\t\t\\return (n + 1)個目の行・列が埋まったときの中央値\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)個目の行・列が埋まったときの最頻値と分布を求める\n\t\t\\param (n + 1)個目の数値n\n\t\t\\param mcresult モンテカルロ・シミュレーションの結果が格納された二次元可変長配列\n\t\t\\return (n + 1)個目の行・列が埋まったときの最頻値と分布のstd::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)個目の行・列が埋まったときの標準偏差を求める\n\t\t\\param avgten (n + 1)個目の行・列が埋まったときの平均試行回数\n\t\t\\param (n + 1)個目の数値n\n\t\t\\param mcresult モンテカルロ・シミュレーションの結果が格納された二次元可変長配列\n\t\t\\return (n + 1)個目の行・列が埋まったときの標準偏差\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        ビンゴボードを生成する\n        \\return ビンゴボードが格納された可変長配列\n    */\n    auto makeboard();\n\n#ifdef _CHECK_PARALELL_PERFORM\n    //! A function.\n    /*!\n        モンテカルロ・シミュレーションを行う\n        \\return モンテカルロ・シミュレーションの結果が格納された二次元可変長配列\n    */\n\tstd::pair<std::vector< std::vector<mypair2> >, std::vector< std::vector<mypair2> > > montecarlo();\n#endif\n\n    //! A function.\n    /*!\n        モンテカルロ・シミュレーションの実装\n        \\param mr 自作乱数クラスのオブジェクト\n        \\return モンテカルロ法の結果が格納された可変長配列\n    */\n\ttemplate <typename MyRandom>\n\tstd::pair<std::vector<mypair2>, std::vector<mypair2> > montecarloImpl(MyRandom & mr);\n\n    //! A function.\n    /*!\n        モンテカルロ・シミュレーションをTBBで並列化して行う\n        \\return モンテカルロ・シミュレーションの結果が格納された二次元可変長配列\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)個目の行・列が埋まったときの分布をcsvファイルに出力する\n\t\t\\param distmap (n + 1)個目の行・列が埋まったときの分布\n\t\t\\param filename ファイル名\n    */\n    void outputcsv(mymap const & distmap, std::string const & filename);\n}\n\nint main()\n{\n    checkpoint::CheckPoint cp;\n\n    cp.checkpoint(\"処理開始\", __LINE__);\n\n#ifdef _CHECK_PARALELL_PERFORM\n    // モンテカルロ・シミュレーションの結果を代入\n    auto const mcresult(montecarlo());\n\n    cp.checkpoint(\"並列化無効\", __LINE__);\n#endif      \n\t\n    // TBBで並列化したモンテカルロ・シミュレーションの結果を代入\n    auto const mcresult2(montecarloTBB());\n\n    cp.checkpoint(\"並列化有効\", __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}個目.csv\", n + 1));\n\n        std::cout \n\t\t\t<< std::format(\"ビンゴ{:d}個目に必要な平均試行回数：{:.1f}回, 効率：{:.1f}(回/個), \", n + 1, trialavg[n], trialavg[n] / static_cast<double>(n + 1))\n\t\t\t<< std::format(\"中央値：{:d}回, 最頻値：{:d}回, 標準偏差：{:.1f}, \", eval_median(mcresult2.first, n), mode, eval_std_deviation(trialavg[n], mcresult2.first, n))\n\t\t\t<< std::format(\"埋まっているマスの平均個数：{:.1f}個\\n\", fillavg[n]);\n#else\n        outputcsv(distmap, (boost::format(\"result/distribution_%d個目.csv\") % (n + 1)).str());\n\n        std::cout\n            << boost::format(\"ビンゴ%d個目に必要な平均試行回数：%.1f回, 効率：%.1f(回/個), \")\n            % (n + 1)\n            % trialavg[n]\n            % (trialavg[n] / static_cast<double>(n + 1))\n            << boost::format(\"中央値：%d回, 最頻値：%d回, 標準偏差：%.1f, \")\n            % eval_median(mcresult2.first, n)\n            % mode\n            % eval_std_deviation(trialavg[n], mcresult2.first, n)\n            << boost::format(\"埋まっているマスの平均個数：%.1f個\\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}個目.csv\", n + 1));\n\n        std::cout\n            << std::format(\"{:d}個目のマスに必要な平均試行回数：{:.1f}回, 効率：{:.1f}(回/個), \", n + 1, trialavg2[n], trialavg2[n] / static_cast<double>(n + 1))\n            << std::format(\"中央値：{:d}回, 最頻値：{:d}回, 標準偏差：{:.1f}, \", eval_median(mcresult2.second, n), mode, eval_std_deviation(trialavg2[n], mcresult2.second, n))\n            << std::format(\"埋まっている行・列の平均個数：{:.1f}個\\n\", fillavg2[n]);\n#else\n\t\toutputcsv(distmap, (boost::format(\"result/distribution2_%d個目.csv\") % (n + 1)).str());\n\n\t\tstd::cout\n\t\t\t<< boost::format(\"%d個目のマスに必要な平均試行回数：%.1f回, 効率：%.1f(回/個), \")\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(\"中央値：%d回, 最頻値：%d回, 標準偏差：%.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(\"埋まっている行・列の平均個数：%.1f個\\n\")\n\t\t\t% fillavg2[n];\n#endif\n\t}\n\n    cp.checkpoint(\"それ以外の処理\", __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        // モンテカルロ・シミュレーションの平均試行回数の結果を格納した可変長配列\n        std::valarray<double> trialavg(size);\n\n        // モンテカルロ・シミュレーションのn回目の試行で、埋まっているマスの数を格納した可変長配列\n        std::valarray<double> fillavg(size);\n\n        // 行・列の総数分繰り返す\n        for (auto n = 0U; n < size; n++) {\n            // 総和を0で初期化\n            auto trialsum = 0;\n            auto fillsum = 0;\n\n            // 試行回数分繰り返す\n            for (auto j = 0U; j < MCMAX; j++) {\n                // j回目の結果を加える\n                trialsum += mcresult[j][n].first;\n                fillsum += mcresult[j][n].second;\n            }\n\n            // 平均を算出してn行・列目のtrialavg、fillavgに代入\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// 中央値を求めるために必要な可変長配列\n\t\tstd::vector<std::int32_t> medtmp(MCMAX);\n\n\t\t// 中央値を求めるために必要な可変長配列を、モンテカルロ法の結果から生成\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// 中央値を求めるためにソートする\n\t\tboost::sort(medtmp);\n\n\t\t// 中央値を求める\n\t\tif constexpr (MCMAX % 2) {\n\t\t\t// 要素が奇数個なら中央の要素を返す\n\t\t\treturn medtmp[(MCMAX - 1) / 2];\n\t\t}\n\t\telse {\n\t\t\t// 要素が偶数個なら中央二つの平均を返す\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)個目の行・列が埋まったときの分布\n\t\tstd::unordered_map<std::int32_t, std::int32_t> distmap;\n\n\t\t// distmapを埋める\n\t\tfor (auto const & res : mcresult) {\n\t\t\t// (n + 1)個目の行・列が埋まったときの回数をkeyとする\n\t\t\tauto const key = res[n].first;\n\n\t\t\t// keyが存在するかどうか\n\t\t\tauto itr = distmap.find(key);\n\t\t\tif (itr == distmap.end()) {\n\t\t\t\t// keyが存在しなかったので、そのキーでハッシュを拡張（値1）\n\t\t\t\tdistmap.emplace(key, 1);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// keyが指す値を更新\n\t\t\t\titr->second++;\n\t\t\t}\n\t\t}\n\n\t\t// 最頻値を探索\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// 最頻値と(n + 1)個目の行・列が埋まったときの分布をpairにして返す\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// 標準偏差を求めるために必要な可変長配列\n\t\tstd::valarray<double> devtmp(MCMAX);\n\n\t\t// 標準偏差の計算\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// 標準偏差を求める\n\t\treturn std::sqrt(devtmp.sum() / static_cast<double>(MCMAX));\n\t}\n\n    auto makeboard()\n    {\n        // 仮のビンゴボードを生成\n        std::vector<std::int32_t> boardtmp(BOARDSIZE);\n\n        // 仮のビンゴボードに1～25の数字を代入\n        boost::algorithm::iota(boardtmp, 1);\n\n        // 仮のビンゴボードの数字をシャッフル\n        std::shuffle(boardtmp.begin(), boardtmp.end(), std::mt19937());\n\n        // ビンゴボードを生成\n        std::vector<mypair> board(BOARDSIZE);\n\n        // 仮のビンゴボードからビンゴボードを生成する\n        boost::transform(\n            boardtmp,\n            board.begin(),\n            [](auto n) { return std::make_pair(n, false); });\n\n        // ビンゴボードを返す\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        // モンテカルロ・シミュレーションの結果を格納するための二次元可変長配列\n\t\tstd::pair<std::vector< std::vector<mypair2> >, std::vector< std::vector<mypair2> > > mcresult;\n\n\t\t// MCMAX個の容量を確保\n\t\tmcresult.first.reserve(MCMAX);\n\t\tmcresult.second.reserve(MCMAX);\n\n#ifdef HAVE_SSE2\n\t\t// 自作乱数クラスを初期化\n\t\tmyrandom::MyRandSfmt mr(1, BOARDSIZE);\n#else\n\t\t// 自作乱数クラスを初期化\n\t\tmyrandom::MyRand mr(1, BOARDSIZE);\n#endif\n        // 試行回数分繰り返す\n        for (auto n = 0U; n < MCMAX; n++) {\n\t\t\t// モンテカルロ・シミュレーションの結果を代入\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        // モンテカルロ・シミュレーションの結果を返す\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        // ビンゴボードを生成\n        auto board(makeboard());\n\n        // その行・列が既に埋まっているかどうかを格納する可変長配列\n        // ROWCOLUMN個の要素をfalseで初期化\n        std::vector<bool> rcfill(ROWCOLUMN, false);\n\n        // 行・列が埋まるまでに要した回数と、その時点で埋まったマスを格納した\n        // 可変長配列\n        std::vector<mypair2> fillnum;\n\n\t\t// (n + 1)個目のマスが埋まったときの回数と、その時点で埋まった行・列を格納した\n        // 可変長配列\n\t\tstd::vector<mypair2> fillnum2;\n\n        // ROWCOLUMN個の容量を確保\n        fillnum.reserve(ROWCOLUMN);\n\n        // その時点で埋まっているマスを計算するためのラムダ式\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        // 無限ループ\n        for (auto n = 1; ; n++) {\n            // 乱数で得た数字で、かつまだ当たってないマスを検索\n            auto itr = boost::find(board, std::make_pair(mr.myrand(), false));\n\n            // そのようなマスがあった\n            if (itr != board.end()) {\n                // そのマスは当たったとし、フラグをtrueにする\n                itr->second = true;\n            }\n            // そのようなマスがなかった\n            else {\n                //ループ続行\n                continue;\n            }\n\n            // 各行・列が埋まったかどうかをチェック\n            for (auto j = 0U; j < ROW; j++) {\n                // 各行が埋まったかどうかのフラグ\n                auto rowflag = true;\n\n                // 各行が埋まったかどうかをチェック\n                for (auto k = 0U; k < COLUMN; k++) {\n                    rowflag &= board[COLUMN * j + k].second;\n                }\n\n                // 行の処理\n                if (rowflag &&\n                    // その行は既に埋まっているかどうか\n                    !rcfill[j]) {\n                    // その行は埋まったとして、フラグをtrueにする\n                    rcfill[j] = true;\n\n                    // 要した試行回数と、その時点で埋まったマスの数を格納\n                    fillnum.emplace_back(n, sum(board));\n                }\n\n                // 各列が埋まったかどうかのフラグ\n                auto columnflag = true;\n\n                // 各列が埋まったかどうかをチェック    \n                for (auto k = 0U; k < ROW; k++) {\n                    columnflag &= board[j + COLUMN * k].second;\n                }\n\n                // 列の処理\n                if (columnflag &&\n                    // その列は既に埋まっているかどうか\n                    !rcfill[j + ROW]) {\n\n                    // その列は埋まったとして、フラグをtrueにする\n                    rcfill[j + ROW] = true;\n\n                    // 要した試行回数と、その時点で埋まったマスの数を格納\n                    fillnum.emplace_back(n, sum(board));\n                }\n            }\n\n\t\t\t// 要した試行回数と、その時点で埋まっている行・列の数を格納\n\t\t\tfillnum2.emplace_back(n, static_cast<std::int32_t>(fillnum.size()));\n\n            // 全ての行・列が埋まったかどうか\n            if (fillnum.size() == ROWCOLUMN) {\n                // 埋まったのでループ脱出\n                break;\n            }\n        }\n\n        // 要した試行関数の可変長配列を返す\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        // モンテカルロ・シミュレーションの結果を格納するための二次元可変長配列\n        // 複数のスレッドが同時にアクセスする可能性があるためtbb::concurrent_vectorを使う\n        std::pair<tbb::concurrent_vector< std::vector<mypair2> >, tbb::concurrent_vector< std::vector<mypair2> > > mcresult;\n\n        // MCMAX個の容量を確保\n        mcresult.first.reserve(MCMAX);\n\t\tmcresult.second.reserve(MCMAX);\n\n        // MCMAX回のループを並列化して実行\n        tbb::parallel_for(\n            0U,\n            MCMAX,\n            1U,\n            [&mcresult](auto) {\n\n#ifdef HAVE_SSE2\n\t\t\t// 自作乱数クラスを初期化\n\t\t\tmyrandom::MyRandSfmt mr(1, BOARDSIZE);\n#else\n\t\t\t// 自作乱数クラスを初期化\n\t\t\tmyrandom::MyRand mr(1, BOARDSIZE);\n#endif\n\n            // モンテカルロ・シミュレーションの結果を代入\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        // モンテカルロ・シミュレーションの結果を返す\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 <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": "\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  [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": "#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": "#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 (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 <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": "#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": "#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": "/* 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 <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": "#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": "#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": "#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 * \\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": "#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": "#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": "#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": "#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": "// 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": "#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": "#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": "// 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": "#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 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": "#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 * 本程序演示如何用 gtsam 进行位姿图优化\n * sphere.g2o 是人工生成的一个 Pose graph，我们来优化它。\n * 与 g2o 相似，在 gtsam 中添加的是因子，相当于误差\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的因子图\n  gtsam::Values::shared_ptr initial(new gtsam::Values);  // 初始值\n  // 从g2o文件中读取节点和边的信息\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      // 顶点\n      gtsam::Key id;\n      fin >> id;\n      double data[7];\n      for (int i = 0; i < 7; i++) fin >> data[i];\n      // 转换至gtsam的Pose3\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));  // 添加初始值\n      cntVertex++;\n    } else if (tag == \"EDGE_SE3:QUAT\") {\n      // 边，对应到因子图中的因子\n      gtsam::Matrix m = gtsam::I_6x6;  // 信息矩阵\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的信息矩阵定义方式与gtsam不同，这里对它进行修改\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);  // 高斯噪声模型\n      gtsam::NonlinearFactor::shared_ptr factor(\n          new gtsam::BetweenFactor<gtsam::Pose3>(id1, id2, gtsam::Pose3(R, t),\n                                                 model)  // 添加一个因子\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  // 固定第一个顶点，在gtsam中相当于添加一个先验因子\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  // 开始因子图优化，配置优化选项\n  cout << \"optimizing the factor graph\" << endl;\n  // 我们使用 LM 优化\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  // 你可以尝试下 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  // 写入 g2o 文件，同样伪装成 g2o 中的顶点和边，以便用 g2o_viewer 查看。\n  // 顶点咯\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  // 边咯\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": "#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": "////////////////////////////////////////////////////////////////////////////////////////////////////\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": "#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": "#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": "//! [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   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": "#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": "#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‐P. 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 \"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": "\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// 像往常一样，第一步是包括一些deal.II和C++头文件的功能。\n\n// 列表中包括一些提供向量、矩阵和预处理类的头文件，这些头文件实现了各自Trilinos类的接口；关于这些的一些更多信息可以在  step-31  中找到。\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// 在这个顶层设计的最后，我们为当前项目开辟一个命名空间，下面的所有材料都将进入这个命名空间，然后将所有deal.II名称导入这个命名空间。\n\nnamespace Step43 \n{ \n  using namespace dealii; \n// @sect3{Boundary and initial value classes}  \n\n// 下面的部分直接取自 step-21 ，所以没有必要重复那里的描述。\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// 在本教程中，我们仍然使用之前在 step-21 中使用的两个渗透率模型，所以我们再次避免对它们进行详细评论。\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// 所有物理量的实现，如总流动性 $\\lambda_t$ 和水的部分流量 $F$ 都来自 step-21 ，所以我们也没有对它们做任何评论。与 step-21 相比，我们增加了检查，即传递给这些函数的饱和度实际上是在物理上有效的范围内。此外，鉴于润湿相以速度 $\\mathbf u F'(S)$ 移动，很明显 $F'(S)$ 必须大于或等于零，所以我们也断言，以确保我们的计算得到的导数公式是合理的。\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// 在这第一部分中，我们定义了一些我们在构建线性求解器和预处理器时需要的类。这一部分与  step-31  中使用的基本相同。唯一不同的是，原来的变量名称stokes_matrix被另一个名称darcy_matrix取代，以配合我们的问题。\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// 定义解决随时间变化的平流主导的两相流问题（或Buckley-Leverett问题[Buckley 1942]）的顶层逻辑的类的定义主要基于教程程序 step-21 和 step-33 ，特别是 step-31 ，我们在这里使用的一般结构基本相同。与 step-31 一样，在下面的实现中需要寻找的关键例程是 <code>run()</code> and <code>solve()</code> 函数。\n\n// 与 step-31 的主要区别是，由于考虑了自适应算子拆分，我们需要多几个成员变量来保存最近两次计算的达西（速度/压力）解，以及当前的达西（直接计算，或从前两次计算中推断），我们需要记住最近两次计算的达西解。我们还需要一个辅助函数来确定我们是否真的需要重新计算达西解。\n\n// 与 step-31 不同，这一步多用了一个AffineConstraints对象，叫做darcy_preconditioner_constraints。这个约束对象只用于为Darcy预处理程序组装矩阵，包括悬挂节点约束以及压力变量的Dirichlet边界值约束。我们需要这个，因为我们正在为压力建立一个拉普拉斯矩阵，作为舒尔补码的近似值），如果应用边界条件，这个矩阵是正定的。\n\n// 这样在这个类中声明的成员函数和变量的集合与  step-31  中的相当相似。\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// 我们接下来会有一些辅助函数，这些函数在整个程序中的不同地方都会用到。\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// 接下来是成员变量，其中大部分与 step-31 中的变量类似，但与速度/压力系统的宏观时间步长有关的变量除外。\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// 在最后，我们声明一个变量，表示材料模型。与 step-21 相比，我们在这里把它作为一个成员变量，因为我们想在不同的地方使用它，所以有一个声明这样一个变量的中心位置，将使我们更容易用另一个类来替换 RandomMedium::KInverse （例如，用 SingleCurvingCrack::KInverse). 替换 RandomMedium::KInverse ）。\n    const RandomMedium::KInverse<dim> k_inverse; \n  }; \n// @sect3{TwoPhaseFlowProblem<dim>::TwoPhaseFlowProblem}  \n\n// 这个类的构造函数是对  step-21  和  step-31  中的构造函数的扩展。我们需要添加涉及饱和度的各种变量。正如介绍中所讨论的，我们将再次使用 $Q_2 \\times Q_1$ （Taylor-Hood）元素来处理Darcy系统，这是一个满足Ladyzhenskaya-Babuska-Brezzi（LBB）条件的元素组合[Brezzi and Fortin 1991, Chen 2005]，并使用 $Q_1$ 元素处理饱和度。然而，通过使用存储Darcy和温度有限元的多项式程度的变量，可以很容易地持续修改这些元素的程度以及在其上使用的所有正交公式的下游。此外，我们还初始化了与算子分割有关的时间步进变量，以及矩阵装配和预处理的选项。\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// 这个函数设置了我们这里的DoFHandler对象（一个用于Darcy部分，一个用于饱和部分），以及将本程序中线性代数所需的各种对象设置为合适的尺寸。其基本操作与 step-31 所做的类似。\n\n// 该函数的主体首先列举了达西和饱和系统的所有自由度。对于Darcy部分，自由度会被排序，以确保速度优先于压力DoF，这样我们就可以将Darcy矩阵划分为一个 $2 \\times 2$ 矩阵。\n//然后，\n//我们需要将悬挂节点约束和Dirichlet边界值约束纳入 darcy_preconditioner_constraints。 边界条件约束只设置在压力分量上，因为对应于非混合形式的多孔介质流算子的Schur complement预处理程序 $-\\nabla \\cdot [\\mathbf K \\lambda_t(S)]\\nabla$  ，只作用于压力变量。因此，我们使用一个过滤掉速度分量的分量掩码，这样就可以只对压力自由度进行缩减。\n\n// 做完这些后，我们计算各个块中的自由度数量。然后，这些信息被用来创建达西和饱和系统矩阵的稀疏模式，以及用于建立达西预处理的预处理矩阵。如同 step-31 ，我们选择使用DynamicSparsityPattern的封锁版本来创建模式。因此，对于这一点，我们遵循与 step-31 相同的方式，对于成员函数的其他部分，我们不必再重复描述。\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// 接下来的几个函数专门用来设置我们在这个程序中必须处理的各种系统和预处理矩阵及右手边。\n\n//  @sect4{TwoPhaseFlowProblem<dim>::assemble_darcy_preconditioner}  \n\n// 这个函数组装我们用于预处理达西系统的矩阵。我们需要的是在速度分量上用 $\\left(\\mathbf{K} \\lambda_t\\right)^{-1}$ 加权的向量质量矩阵和在压力分量上用 $\\left(\\mathbf{K} \\lambda_t\\right)$ 加权的质量矩阵。我们首先生成一个适当阶数的正交对象，即FEValues对象，可以给出正交点的数值和梯度（连同正交权重）。接下来我们为单元格矩阵和局部与全局DoF之间的关系创建数据结构。向量phi_u和grad_phi_p将保存基函数的值，以便更快地建立局部矩阵，正如在  step-22  中已经做的。在我们开始对所有活动单元进行循环之前，我们必须指定哪些成分是压力，哪些是速度。\n\n// 局部矩阵的创建是相当简单的。只有一个由 $\\left(\\mathbf{K} \\lambda_t\\right)^{-1}$ 加权的项（关于速度）和一个由 $\\left(\\mathbf{K} \\lambda_t\\right)$ 加权的拉普拉斯矩阵需要生成，所以局部矩阵的创建基本上只需要两行就可以完成。由于该文件顶部的材料模型函数只提供了渗透率和迁移率的倒数，我们必须根据给定的数值手工计算 $\\mathbf K$ 和 $\\lambda_t$ ，每个正交点一次。\n\n// 一旦本地矩阵准备好了（在每个正交点上对本地矩阵的行和列进行循环），我们就可以得到本地的DoF指数，并将本地信息写入全局矩阵中。我们通过直接应用约束条件（即darcy_preconditioner_constraints）来做到这一点，该约束条件负责处理悬挂节点和零Dirichlet边界条件约束。这样做，我们就不必事后再做，以后也不必使用 AffineConstraints::condense 和 MatrixTools::apply_boundary_values, 这两个需要修改矩阵和向量项的函数，因此对于我们不能立即访问单个内存位置的特里诺斯类来说，很难编写。\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// 在调用上述函数组装预处理矩阵后，该函数生成将用于舒尔补块预处理的内部预处理器。前置条件需要在每个饱和时间步长时重新生成，因为它们取决于随时间变化的饱和度  $S$  。\n\n// 在这里，我们为速度-速度矩阵  $\\mathbf{M}^{\\mathbf{u}}$  和Schur补码  $\\mathbf{S}$  设置了预处理器。正如介绍中所解释的，我们将使用一个基于矢量矩阵 $\\mathbf{M}^{\\mathbf{u}}$ 的IC预处理器和另一个基于标量拉普拉斯矩阵 $\\tilde{\\mathbf{S}}^p$ 的IC预处理器（它在频谱上与达西矩阵的舒尔补码接近）。通常， TrilinosWrappers::PreconditionIC 类可以被看作是一个很好的黑盒预处理程序，不需要对矩阵结构和/或背后的算子有任何特殊的了解。\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// 这是为达西系统组装线性系统的函数。\n\n// 关于执行的技术细节，其程序与  step-22  和  step-31  中的程序相似。我们重置矩阵和向量，在单元格上创建正交公式，然后创建相应的FEValues对象。\n\n// 有一件事需要评论：由于我们有一个单独的有限元和DoFHandler来处理饱和问题，我们需要生成第二个FEValues对象来正确评估饱和解。要实现这一点并不复杂：只需使用饱和结构，并为基函数值设置一个更新标志，我们需要对饱和解进行评估。这里需要记住的唯一重要部分是，两个FEValues对象使用相同的正交公式，以确保我们在循环计算两个对象的正交点时获得匹配的信息。\n\n// 声明的过程中，对数组的大小、本地矩阵的创建、右手边以及与全局系统相比较的本地道夫指数的向量都有一些快捷方式。\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// 接下来我们需要一个向量，该向量将包含前一时间层在正交点的饱和解的值，以组装达西方程中的饱和相关系数。\n\n// 我们接下来创建的向量集包含了基函数的评价以及它们的梯度，将用于创建矩阵。把这些放到自己的数组中，而不是每次都向FEValues对象索取这些信息，是为了加速装配过程的优化，详情请见 step-22 。\n\n// 最后两个声明是用来从整个FE系统中提取各个块（速度、压力、饱和度）的。\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// 现在开始对问题中的所有单元格进行循环。我们在这个装配例程中使用了两个不同的DoFHandlers，所以我们必须为使用中的两个对象设置两个不同的单元格迭代器。这可能看起来有点奇怪，但是由于达西系统和饱和系统都使用相同的网格，我们可以假设这两个迭代器在两个DoFHandler对象的单元格中同步运行。\n\n// 循环中的第一条语句又是非常熟悉的，按照更新标志的规定对有限元数据进行更新，将局部数组清零，并得到正交点上的旧解的值。 在这一点上，我们还必须在正交点上获得前一个时间步长的饱和函数的值。为此，我们可以使用 FEValues::get_function_values （之前已经在 step-9 、 step-14 和 step-15 中使用），这个函数接收一个解向量，并返回当前单元的正交点的函数值列表。事实上，它返回每个正交点的完整矢量值解，即不仅是饱和度，还有速度和压力。\n\n// 然后，我们就可以在单元格上的正交点上进行循环，以进行积分。这方面的公式直接来自介绍中所讨论的内容。\n\n// 一旦这样做了，我们就开始在局部矩阵的行和列上进行循环，并将相关的乘积输入矩阵中。\n\n// 循环所有单元的最后一步是将本地贡献输入到全局矩阵和向量结构中，并在local_dof_indices中指定位置。同样，我们让AffineConstraints类将单元格矩阵元素插入到全局矩阵中，全局矩阵已经浓缩了悬挂节点的约束。\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// 这个函数是为了组装饱和传输方程的线性系统。如果有必要，它会调用另外两个成员函数：assemble_saturation_matrix()和assemble_saturation_rhs()。前一个函数然后组装饱和度矩阵，只需要偶尔改变。另一方面，后一个组装右手边的函数必须在每个饱和时间步骤中调用。\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// 这个函数很容易理解，因为它只是通过基函数phi_i_s和phi_j_s为饱和线性系统的左侧形成一个简单的质量矩阵。最后，像往常一样，我们通过在local_dof_indices中指定位置将局部贡献输入全局矩阵。这是通过让AffineConstraints类将单元矩阵元素插入全局矩阵来完成的，全局矩阵已经浓缩了悬挂节点约束。\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// 这个函数是用来组装饱和传输方程的右边。在进行这项工作之前，我们必须为达西系统和饱和系统分别创建两个FEValues对象，此外，还必须为这两个系统创建两个FEFaceValues对象，因为我们在饱和方程的弱形式中存在一个边界积分项。对于饱和系统的FEFaceValues对象，我们还需要法向量，我们使用update_normal_vectors标志来申请。\n\n// 接下来，在对所有单元进行循环之前，我们必须计算一些参数（例如global_u_infty、global_S_variation和global_Omega_diameter），这是人工黏度 $\\nu$ 需要的。这与 step-31 中的做法基本相同，所以你可以在那里看到更多的信息。\n\n// 真正的工作是从循环所有的饱和和Darcy单元开始的，以便将局部贡献放到全局矢量中。在这个循环中，为了简化实现，我们把一些工作分成两个辅助函数：assemble_saturation_rhs_cell_term和assemble_saturation_rhs_boundary_term。 我们注意到，我们在这两个函数中把细胞或边界贡献插入全局向量，而不是在本函数中。\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// 这个函数负责整合饱和度方程右边的单元项，然后将其组装成全局右边的矢量。鉴于介绍中的讨论，这些贡献的形式很清楚。唯一棘手的部分是获得人工黏度和计算它所需的一切。该函数的前半部分专门用于这项任务。\n\n// 该函数的最后一部分是将局部贡献复制到全局向量中，其位置由local_dof_indices指定。\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// 下一个函数负责饱和方程右侧形式中的边界积分项。 对于这些，我们必须计算全局边界面上的上行通量，也就是说，我们只对全局边界的流入部分弱加迪里切特边界条件。如前所述，这在 step-21 中已经描述过了，所以我们不对其进行更多的描述。\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// 该函数实现了算子分割算法，即在每个时间步长中，它要么重新计算达西系统的解，要么从以前的时间步长中推算出速度/压力，然后确定时间步长的大小，然后更新饱和度变量。其实现主要遵循  step-31  中的类似代码。除了run()函数外，它是本程序中的核心函数。\n\n// 在函数的开始，我们询问是否要通过评估后验准则来解决压力-速度部分（见下面的函数）。如果有必要，我们将使用GMRES求解器和Schur补充块预处理来求解压力-速度部分，如介绍中所述。\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// 另一方面，如果我们决定不计算当前时间步长的达西系统的解，那么我们需要简单地将前两个达西解外推到与我们计算速度/压力的时间相同。我们做一个简单的线性外推，即给定从上次计算达西解到现在的宏观时间步长 $dt$ （由 <code>current_macro_time_step</code> 给出），以及 $DT$ 上一个宏观时间步长（由 <code>old_macro_time_step</code> 给出），然后得到 $u^\\ast = u_p + dt \\frac{u_p-u_{pp}}{DT} = (1+dt/DT)u_p - dt/DT u_{pp}$  ，其中 $u_p$ 和 $u_{pp}$ 是最近两个计算的达西解。我们只需用两行代码就可以实现这个公式。\n\n// 请注意，这里的算法只有在我们至少有两个先前计算的Darcy解，我们可以从中推断出当前的时间，这一点通过要求重新计算前两个时间步骤的Darcy解来保证。\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// 用这样计算出来的速度矢量，根据介绍中讨论的CFL标准计算出最佳时间步长......\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// ......然后在我们处理时间步长的时候，还要更新我们使用的宏观时间步长。具体而言，这涉及到。(i) 如果我们刚刚重新计算了达西解，那么之前的宏观时间步长现在是固定的，当前的宏观时间步长，到现在为止，只是当前（微观）时间步长。(ii) 如果我们没有重新计算达西解，那么当前的宏观时间步长刚刚增长了 <code>time_step</code>  。\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// 这个函数的最后一步是根据我们刚刚得到的速度场重新计算饱和解。这自然发生在每一个时间步骤中，我们不会跳过这些计算。在计算饱和度的最后，我们投射回允许的区间 $[0,1]$ ，以确保我们的解保持物理状态。\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// 下一个函数是对网格进行细化和粗化。它的工作分三块进行。(i) 计算细化指标，方法是通过使用各自的时间步长（如果这是第一个时间步长，则取唯一的解决方案），从前两个时间步长中线性推断出的解决方案向量的梯度。(ii) 在梯度大于或小于某一阈值的单元中标记出细化和粗化的单元，保留网格细化的最小和最大水平。(iii) 将解决方案从旧网格转移到新网格。这些都不是特别困难。\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// 这个函数生成图形输出。它实质上是对  step-31  中实现的复制。\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// 这个函数实现了自适应运算符拆分的后验标准。考虑到我们在上面实现其他函数的方式，并考虑到论文中得出的准则公式，该函数是相对简单的。\n\n// 如果我们决定要采用原始的IMPES方法，即在每个时间步长中求解Darcy方程，那么可以通过将阈值 <code>AOS_threshold</code> （默认为 $5.0$ ）设置为0来实现，从而迫使该函数总是返回true。\n\n// 最后，请注意，该函数在前两个时间步骤中无条件地返回真，以确保我们在跳过达西系统的解时总是至少解了两次，从而允许我们从 <code>solve()</code> 中的最后两次解中推算出速度。\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// 下一个函数只是确保饱和度值始终保持在  $[0,1]$  的物理合理范围内。虽然连续方程保证了这一点，但离散方程并没有。然而，如果我们允许离散解逃脱这个范围，我们就会遇到麻烦，因为像 $F(S)$ 和 $F'(S)$ 这样的项会产生不合理的结果（例如 $F'(S)<0$ 为 $S<0$ ，这将意味着润湿液相的流动方向为<i>against</i>的散流体速度））。因此，在每个时间步骤结束时，我们只需将饱和场投射回物理上合理的区域。\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// 另一个比较简单的辅助函数。计算总速度乘以分数流函数的导数的最大值，即计算  $\\|\\mathbf{u} F'(S)\\|_{L_\\infty(\\Omega)}$  。这个项既用于时间步长的计算，也用于人工黏度中熵留项的正常化。\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// 为了计算稳定化项，我们需要知道饱和变量的范围。与 step-31 不同，这个范围很容易被区间 $[0,1]$ 所约束，但是我们可以通过在正交点的集合上循环，看看那里的值是多少，从而做得更好。如果可以的话，也就是说，如果周围至少有两个时间步长，我们甚至可以把这些值推算到下一个时间步长。\n\n// 和以前一样，这个函数是在对  step-31  进行最小修改后取的。\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// 最后一个工具函数是用来计算给定单元上的人工粘度的。如果你面前有它的公式，这并不特别复杂，看一下  step-31  中的实现。与那个教程程序的主要区别是，这里的速度不是简单的 $\\mathbf u$ ，而是 $\\mathbf u F'(S)$ ，一些公式需要做相应的调整。\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// 除了 <code>solve()</code> 之外，这个函数是这个程序的主要功能，因为它控制了迭代的时间，以及何时将解决方案写入输出文件，何时进行网格细化。\n\n// 除了启动代码通过 <code>goto start_time_iteration</code> 标签循环回到函数的开头外，一切都应该是相对简单的。无论如何，它模仿了  step-31  中的相应函数。\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// 主函数看起来与所有其他程序几乎一样。对于使用Trilinos的程序来说，需要初始化MPI子系统--即使是那些实际上没有并行运行的程序--在  step-31  中有解释。\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// 这个程序只能在串行中运行。否则，将抛出一个异常。\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": "#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": "/* =========================================================================\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": "\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": "/* =========================================================================\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": "/**\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": "//=======================================================================\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 φ is the geographical latitude\n// ST is the Local Sidereal Time\n// ε 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": "#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": "//=======================================================================\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// 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": "#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": "#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": "///////////////////////////////////////////////////////////////////////////////\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": "//==================================================================================================\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// 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": "#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": "/******************************************************************************\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érifier 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érifier 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änkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#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": "/**\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": "// 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": "/* plantcalc -- Power plant modelling\n * (c) 2012 Michał Górny\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": "//  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// 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": "#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": "#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": "/* =========================================================================\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": "//\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": "//\r\n//! Copyright © 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": "/*\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änkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <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": "#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": "\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}  这个程序是基于 step-7  、 step-20  和  step-51  ，所以下面的头文件大部分是熟悉的。我们需要以下文件，其中只有导入FE_DGRaviartThomas类的文件（即`deal.II/fe/fe_dg_vector.h`）是真正的新文件；FE_DGRaviartThomas实现了介绍中讨论的 \"破碎 \"Raviart-Thomas空间。\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// 我们的第一步，像往常一样，是把所有与本教程程序有关的东西放到自己的命名空间中。\n\nnamespace Step61 \n{ \n  using namespace dealii; \n// @sect3{The WGDarcyEquation class template}  \n\n// 这是本程序的主类。我们将使用弱加勒金（WG）方法求解内部和面上的数值压力，并计算出压力的 $L_2$ 误差。在后处理步骤中，我们还将计算速度和通量的 $L_2$  误差。\n\n// 该类的结构与以前的教程程序没有根本的不同，所以除了一个例外，没有必要对细节进行评论。该类有一个成员变量`fe_dgrt`，对应于介绍中提到的 \"破碎 \"的Raviart-Thomas空间。还有一个与之匹配的`dof_handler_dgrt`，表示从这个元素创建的有限元场的全局枚举，还有一个向量`darcy_velocity`，用于保持这个场的节点值。在求解压力后，我们将使用这三个变量来计算一个后处理的速度场，然后我们可以对其进行误差评估，并将其输出用于可视化。\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// 接下来，我们定义系数矩阵 $\\mathbf{K}$ （这里是身份矩阵），迪里希特边界条件，右手边 $f = 2\\pi^2 \\sin(\\pi x) \\sin(\\pi y)$  ，以及与这些选择相对应的 $K$ 和 $f$ 的精确解，即 $p = \\sin(\\pi x) \\sin(\\pi y)$  。\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// 实现精确压力解决方案的类有一个奇怪的地方，我们把它作为一个有两个分量的向量值来实现。(我们在构造函数中说它有两个分量，在这里我们调用基函数类的构造函数)。在`value()`函数中，我们不测试`component`参数的值，这意味着我们为向量值函数的两个分量返回相同的值。我们这样做是因为我们将本程序中使用的有限元描述为一个包含内部和界面压力的矢量值系统，当我们计算误差时，我们希望使用相同的压力解来测试这两个分量。\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// 在这个构造函数中，我们创建了一个矢量值函数的有限元空间，这里将包括用于内部和界面压力的函数， $p^\\circ$  和  $p^\\partial$  。\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// 我们在单位平方域上生成一个网格并对其进行细化。\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// 在我们创建了上面的网格后，我们分配自由度并调整矩阵和向量的大小。这个函数中唯一值得关注的部分是我们如何插值压力的边界值。由于压力由内部和界面分量组成，我们需要确保我们只插值到矢量值解空间中与界面压力相对应的分量上（因为这些分量是唯一定义在域的边界上的）。我们通过一个只针对界面压力的分量屏蔽对象来做到这一点。\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// 在双线性形式中，在两个相邻单元之间的面上没有积分项，所以我们可以直接使用 <code>DoFTools::make_sparsity_pattern</code> 来计算稀疏矩阵。\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// 这个函数比较有趣。正如介绍中所详述的，线性系统的装配要求我们评估形状函数的弱梯度，这是Raviart-Thomas空间的一个元素。因此，我们需要定义一个Raviart-Thomas有限元对象，并有FEValues对象在正交点评估它。然后我们需要计算每个单元 $K$ 上的矩阵 $C^K$ ，为此我们需要介绍中提到的矩阵 $M^K$ 和 $G^K$ 。\n\n// 有一点可能不是很明显，在之前所有的教程程序中，我们总是用DoFHandler的单元格迭代器来调用 FEValues::reinit() 。这样就可以调用诸如 FEValuesBase::get_function_values() 这样的函数，在单元格的正交点上提取有限元函数的值（用DoF值的矢量表示）。为了使这种操作发挥作用，人们需要知道哪些向量元素对应于给定单元上的自由度--也就是说，正是DoFHandler类所提供的那种信息和操作。\n\n// 我们可以为 \"破碎的 \"Raviart-Thomas空间创建一个DoFHandler对象（使用FE_DGRT类），但是我们在这里真的不想这样做。至少在当前函数中，我们不需要任何与这个破碎空间相关的全局定义的自由度，而只需要引用当前单元上的这种空间的形状函数。因此，我们利用这样一个事实，即人们也可以用单元格迭代器来调用 FEValues::reinit() 的Triangulation对象（而不是DoFHandler对象）。在这种情况下，FEValues当然只能为我们提供只引用单元格的信息，而不是这些单元格上列举的自由度。所以我们不能使用 FEValuesBase::get_function_values(), ，但我们可以使用 FEValues::shape_value() 来获取当前单元上正交点的形状函数值。下面我们要利用的就是这种功能。下面给我们提供Raviart-Thomas函数信息的变量是`fe_values_rt`（和相应的`fe_face_values_rt`）对象。\n\n// 鉴于上述介绍，下面的声明应该是非常明显的。\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// 接下来，让我们声明介绍中讨论的各种单元格矩阵。\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// 我们需要  <code>FEValuesExtractors</code>  来访问形状函数的  @p interior  和  @p face  部分。\n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure_interior(0); \n    const FEValuesExtractors::Scalar pressure_face(1); \n\n// 这最终让我们在所有单元格上进行循环。在每个单元中，我们将首先计算用于构建局部矩阵的各种单元矩阵--因为它们取决于相关的单元，所以它们需要在每个单元中重新计算。我们还需要Raviart-Thomas空间的形状函数，为此我们需要首先创建一个通往三角化单元的迭代器，我们可以通过从指向DoFHandler的单元中的赋值来获得。\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// 我们要计算的第一个单元矩阵是拉维-托马斯空间的质量矩阵。 因此，我们需要循环计算速度FEValues对象的所有正交点。\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// 接下来我们通过使用 FullMatrix::gauss_jordan(). 对这个矩阵进行求逆 它将被用来计算后面的系数矩阵 $C^K$ 。值得一提的是，后面的 \"cell_matrix_M \"实际上包含了*的逆*。\n//在这个调用之后的 $M^K$ 的*逆。\n\n        cell_matrix_M.gauss_jordan(); \n\n// 从介绍中，我们知道定义 $C^K$ 的方程的右边 $G^K$ 是面积分和单元积分的区别。在这里，我们对内部的贡献的负值进行了近似。这个矩阵的每个分量都是多项式空间的一个基函数与拉维-托马斯空间的一个基函数的发散之间的乘积的积分。这些基函数是在内部定义的。\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// 接下来，我们用正交法对面的积分进行近似。每个分量都是多项式空间的基函数与Raviart-Thomas空间的基函数与法向量的点积的积分。所以我们在元素的所有面上循环，得到法向量。\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 是 $G^K$ 的转置与质量矩阵的逆之间的矩阵乘积（该逆存储在 @p cell_matrix_M): 中）。\n        cell_matrix_G.Tmmult(cell_matrix_C, cell_matrix_M); \n\n// 最后我们可以计算出本地矩阵  $A^K$  。 元素  $A^K_{ij}$  由  $\\int_{E} \\sum_{k,l} C_{ik} C_{jl} (\\mathbf{K} \\mathbf{v}_k) \\cdot \\mathbf{v}_l \\mathrm{d}x$  得到。我们在上一步已经计算了系数 $C$ ，因此在适当地重新排列循环后得到以下结果。\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// 接下来，我们计算右手边， $\\int_{K} f q \\mathrm{d}x$  。\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// 最后一步是将本地矩阵的组件分配到系统矩阵中，并将单元格右侧的组件转移到系统右侧。\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// 这一步相当琐碎，与之前的许多教程程序相同。\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// 在这个函数中，根据之前计算的压力解计算出速度场。速度被定义为 $\\mathbf{u}_h = \\mathbf{Q}_h \\left(-\\mathbf{K}\\nabla_{w,d}p_h \\right)$ ，这需要我们计算许多与系统矩阵组装相同的项。还有一些矩阵 $E^K,D^K$ 我们也需要组装（见介绍），但它们实际上只是遵循相同的模式。\n\n// 在这里计算与我们在`assemble_system()`函数中已经完成的相同的矩阵，当然是浪费CPU时间的。同样地，我们把那里的一些代码复制到这个函数中，这通常也是一个糟糕的主意。一个更好的实现可能会提供一个函数来封装这些重复的代码。我们也可以考虑使用计算效率和内存效率之间的经典权衡，在装配过程中每个单元只计算一次 $C^K$ 矩阵，把它们存储在边上的某个地方，然后在这里重新使用它们。例如， step-51 就是这样做的，`assemble_system()`函数需要一个参数来决定是否重新计算本地矩阵，类似的方法--也许是将本地矩阵存储在其他地方--可以适用于当前的程序）。\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// 在介绍中，我们解释了如何计算单元上的数值速度。我们需要每个单元上的压力解值、格拉姆矩阵的系数和 $L_2$ 投影的系数。我们已经计算了全局解，所以我们将从全局解中提取单元解。格拉姆矩阵的系数在我们计算压力的系统矩阵时已经计算过了。我们在这里也要这样做。对于投影的系数，我们做矩阵乘法，即用格拉姆矩阵的倒数乘以 $(\\mathbf{K} \\mathbf{w}, \\mathbf{w})$ 的矩阵作为组成部分。然后，我们将所有这些系数相乘，称之为β。数值速度是贝塔和拉维尔特-托马斯空间的基础函数的乘积。\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// 这个 <code>cell_matrix_E</code> 的分量是 $(\\mathbf{K} \\mathbf{w}, \\mathbf{w})$ 的积分。  <code>cell_matrix_M</code> 是格拉姆矩阵。\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// 为了计算介绍中提到的矩阵 $D$ ，我们就需要按照介绍中的解释来评估 $D=M^{-1}E$ 。\n\n        cell_matrix_M.gauss_jordan(); \n        cell_matrix_M.mmult(cell_matrix_D, cell_matrix_E); \n\n// 然后，我们还需要再次计算矩阵 $C$ ，用于评估弱离散梯度。这与组装系统矩阵时使用的代码完全相同，所以我们只需从那里复制它。\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// 最后，我们需要提取对应于当前单元的压力未知数。\n\n        cell->get_dof_values(solution, cell_solution); \n\n// 我们现在可以计算当地的速度未知数（相对于我们将 $-\\mathbf K \\nabla_{w,d} p_h$ 项投影到的Raviart-Thomas空间而言）。\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// 我们计算达西速度。这与cell_velocity相同，但用于绘制Darcy速度图。\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// 这一部分是为了计算压力的 $L_2$ 误差。 我们定义一个向量，用来保存每个单元上的误差规范。接下来，我们使用 VectorTool::integrate_difference() 来计算每个单元上的 $L_2$ 准则的误差。然而，我们实际上只关心解向量的内部分量的误差（我们甚至不能评估正交点的界面压力，因为这些都位于单元格的内部），因此必须使用一个权重函数，确保解变量的界面分量被忽略。这是通过使用ComponentSelectFunction来实现的，其参数表明我们要选择哪个分量（零分量，即内部压力）以及总共有多少分量（两个）。\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// 在这个函数中，我们评估每个单元的速度的 $L_2$ 误差，以及面的流量的 $L_2$ 误差。该函数依赖于之前计算过的`compute_postprocessed_velocity()`函数，该函数根据之前计算过的压力解来计算速度场。\n\n// 我们将评估每个单元的速度，并计算数值速度和精确速度之间的差异。\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// 在之前计算了后处理的速度之后，我们在这里只需要提取每个单元和面的相应数值，并与精确的数值进行比较。\n\n    for (const auto &cell_dgrt : dof_handler_dgrt.active_cell_iterators()) \n      { \n        fe_values_dgrt.reinit(cell_dgrt); \n\n// 首先计算后处理的速度场与精确速度场之间的 $L_2$ 误差。\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// 为了重建通量，我们需要单元格和面的大小。由于通量是按面计算的，我们必须在每个单元的所有四个面上进行循环。为了计算面的速度，我们从之前计算的`darcy_velocity`中提取正交点的值。然后，我们计算法线方向的速度平方误差。最后，我们通过对面和单元面积的适当缩放来计算单元上的 $L_2$ 通量误差，并将其加入全局误差。\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// 将所有单元和面的误差相加后，我们进行平方根计算，得到速度和流量的 $L_2$ 误差。我们将这些数据输出到屏幕上。\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// 我们有两组结果要输出：内部解和骨架解。我们使用 <code>DataOut</code> 来显示内部结果。骨架结果的图形输出是通过使用DataOutFaces类完成的。\n\n// 在这两个输出文件中，内部和面的变量都被存储。对于界面输出，输出文件只是包含了内部压力对面的插值，但是因为没有确定从两个相邻的单元中得到的是哪一个内部压力变量，所以在界面输出文件中最好是忽略内部压力。相反，对于单元格内部输出文件，当然不可能显示任何界面压力 $p^\\partial$ ，因为这些压力只适用于界面，而不是单元格内部。因此，你会看到它们被显示为一个无效的值（比如一个无穷大）。\n\n// 对于单元内部的输出，我们还想输出速度变量。这有点棘手，因为它生活在同一个网格上，但使用不同的DoFHandler对象（压力变量生活在`dof_handler`对象上，达西速度生活在`dof_handler_dgrt`对象上）。幸运的是， DataOut::add_data_vector() 函数有一些变化，允许指定一个矢量对应的DoFHandler，因此我们可以在同一个文件中对两个DoFHandler对象的数据进行可视化。\n\n  template <int dim> \n  void WGDarcyEquation<dim>::output_results() const \n  { \n    { \n      DataOut<dim> data_out; \n\n// 首先将压力解决方案附加到DataOut对象上。\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// 然后对达西速度场做同样的处理，并继续将所有内容写进文件。\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// 这是主类的最后一个函数。它调用我们类的其他函数。\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// 这是主函数。我们可以在这里改变维度以在3D中运行。\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": "//// 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 <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// // 像素坐标转相机归一化坐标\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      //   //-- 读取图像\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 << \"第二個: \" <<  \"一共找到了\" << matches.size() << \"组匹配点\" << 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 << \"第一個: \" <<\"一共找到了\" << matches.size() << \"组匹配点\" << endl;\n      // }\n      \n      // 建立3D点\n      //Mat d1 = imread(depth1, IMREAD_UNCHANGED);       // 深度图为16位无符号数，单通道图像\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为旋转向量形式，用Rodrigues公式转换为矩阵\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  // 构建图优化，先设定g2o\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> BlockSolverType;  // pose is 6, landmark is 3\n  typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType; // 线性求解器类型\n  // 梯度下降方法，可以从GN, LM, DogLeg 中选\n  auto solver = new g2o::OptimizationAlgorithmGaussNewton(\n  g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));\n  g2o::SparseOptimizer optimizer;     // 图模型\n  optimizer.setAlgorithm(solver);   // 设置求解器\n  optimizer.setVerbose(true);       // 打开调试输出\n\n  // 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 <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": "#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": "// g2o - General Graph Optimization\n// Copyright (C) 2012 R. Kümmerle\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": "//==================================================================================================\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": "// 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": "#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": "/* 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": "/* 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": "// 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": "/**\n * Copyright (c) 2018, University Osnabrück\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ück 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ück 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∊ \" << center << \"±\" << 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∊ \" << center << \"±\" << 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∊ \" << center << \"±\" << 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": "#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": "/***************************************************************************\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 <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": "#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": "// 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": "#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": "#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// $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": "// 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": "/* 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": "\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// 像往常一样，程序以一个相当长的包含文件列表开始，你现在可能已经习惯了。\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// 只有这一条是新的：它声明了一个动态稀疏模式（DynamicSparsityPattern）类，我们将在下面进一步使用和解释。\n\n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n\n// 我们将使用C++标准库中的 std::find 算法，所以我们必须包括以下文件来声明它。\n\n#include <algorithm> \n#include <iostream> \n#include <iomanip> \n#include <cmath> \n\n// 最后一步和以前所有的程序一样。\n\nnamespace Step11 \n{ \n  using namespace dealii; \n\n// 然后我们声明一个表示拉普拉斯问题解决方案的类。由于这个例子程序是基于 step-5 ，这个类看起来相当相同，唯一的结构区别是函数 <code>assemble_system</code> now calls <code>solve</code> 本身，因此被称为 <code>assemble_and_solve</code> ，而且输出函数被删除，因为解函数非常无聊，不值得查看。\n\n// 其他唯一值得注意的变化是，构造函数取一个值，代表以后要使用的映射的多项式程度，而且它还有一个成员变量，正好代表这个映射。一般来说，这个变量在实际应用中会出现在声明或使用有限元的相同地方。\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// 构建这样一个对象，通过初始化变量。这里，我们使用线性有限元（ <code>fe</code> 变量的参数表示多项式的度数），以及给定阶数的映射。将我们要做的事情打印到屏幕上。\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// 第一个任务是为这个问题设置变量。这包括生成一个有效的 <code>DoFHandler</code> 对象，以及矩阵的稀疏模式，和代表边界上自由度平均值为零的约束条件的对象。\n\n  template <int dim> \n  void LaplaceProblem<dim>::setup_system() \n  { \n\n// 第一个任务很简单：生成一个自由度的枚举，并将解和右手向量初始化为正确的大小。\n\n    dof_handler.distribute_dofs(fe); \n    solution.reinit(dof_handler.n_dofs()); \n    system_rhs.reinit(dof_handler.n_dofs()); \n\n// 下一个任务是构建代表约束的对象，即边界上自由度的平均值应该是零。为此，我们首先需要一个实际在边界上的节点的列表。 <code>DoFTools</code> 命名空间有一个函数可以返回一个IndexSet对象，该对象包含所有在边界上的自由度的指数。\n\n// 一旦我们有了这个索引集，我们想知道哪个是对应于边界上的自由度的第一个索引。我们需要这个，因为我们想通过边界上所有其他自由度的值来约束边界上的一个节点。使用IndexSet类很容易得到这个 \"第一个 \"自由度的索引。\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// 然后生成一个只有这一个约束的约束对象。首先清除所有以前的内容（这些内容可能来自以前在更粗的网格上的计算），然后添加这一行，将 <code>first_boundary_dof</code> 约束到其他边界DoF的总和，每一个权重为-1。最后，关闭约束对象，也就是说，对它做一些内部记录，以便更快地处理后面的内容。\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// 下一个任务是生成一个稀疏模式。这的确是一个棘手的任务。通常情况下，我们只需调用 <code>DoFTools::make_sparsity_pattern</code> 并使用悬挂节点约束来浓缩结果。我们在这里没有悬挂节点约束（因为我们在这个例子中只进行全局细化），但是我们在边界上有这个全局约束。在这种情况下，这带来了一个严重的问题： <code>SparsityPattern</code> 类希望我们事先说明每行的最大条目数，可以是所有行的，也可以是每行单独的。在库中有一些函数可以告诉你这个数字，如果你只有悬空的节点约束的话（即 DoFHandler::max_couplings_between_dofs), ，但这对现在的情况来说是怎样的？困难的出现是因为消除约束的自由度需要在矩阵中增加一些条目，而这些条目的位置并不那么容易确定。因此，如果我们在这里给出每行的最大条目数，我们就会有一个问题。\n\n// 由于这可能非常困难，以至于无法给出合理的答案，只能分配合理的内存量，所以有一个DynamicSparsityPattern类，它可以帮助我们解决这个问题。它不要求我们事先知道行可以有多少个条目，而是允许任何长度。因此，在你对行的长度没有很好的估计的情况下，它明显更灵活，但是代价是建立这样一个模式也比建立一个你事先有信息的模式要昂贵得多。尽管如此，由于我们在这里没有其他选择，我们将建立这样一个对象，用矩阵的尺寸初始化它，并调用另一个函数 <code>DoFTools::make_sparsity_pattern</code> 来获得由于微分算子引起的稀疏模式，然后用约束对象浓缩它，在稀疏模式中增加那些消除约束所需的位置。\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// 最后，一旦我们有了完整的模式，我们就可以从中初始化一个 <code>SparsityPattern</code> 类型的对象，并反过来用它初始化矩阵。请注意，这实际上是必要的，因为与 <code>SparsityPattern</code> 类相比，DynamicSparsityPattern的效率非常低，因为它必须使用更灵活的数据结构，所以我们不可能将稀疏矩阵类建立在它的基础上，而是需要一个 <code>SparsityPattern</code> 类型的对象，我们通过复制中间对象产生这个对象。\n\n// 作为进一步的附带说明，你会注意到我们在这里没有明确的  <code>compress</code>  稀疏模式。当然，这是由于 <code>copy_from</code> 函数从一开始就生成了一个压缩对象，你不能再向其添加新的条目。因此， <code>compress</code> 的调用是隐含在 <code>copy_from</code> 的调用中的。\n\n    sparsity_pattern.copy_from(dsp); \n    system_matrix.reinit(sparsity_pattern); \n  } \n\n// 下一个函数接着组装线性方程组，对其进行求解，并对解进行评估。这样就有了三个动作，我们将把它们放到八个真实的语句中（不包括变量的声明，以及临时向量的处理）。因此，这个函数是为非常懒惰的人准备的。尽管如此，所调用的函数是相当强大的，通过它们，这个函数使用了整个库的大量内容。但让我们来看看每一个步骤。\n\n  template <int dim> \n  void LaplaceProblem<dim>::assemble_and_solve() \n  { \n\n// 首先，我们要把矩阵和右手边的内容组合起来。在之前的所有例子中，我们已经研究了如何手动完成这一工作的各种方法。然而，由于拉普拉斯矩阵和简单的右手边在应用中出现的频率很高，库中提供的函数实际上是为你做这件事的，也就是说，它们在所有单元格上进行循环，设置局部的矩阵和向量，并将它们放在一起，得到最终结果。\n\n// 以下是两个最常用的函数：创建拉普拉斯矩阵和创建来自体或边界力的右侧向量。它们需要映射对象、代表自由度和使用中的有限元的 <code>DoFHandler</code> 对象、要使用的正交公式以及输出对象。创建右手向量的函数还必须接受一个描述（连续）右手向量函数的函数对象。\n\n// 让我们来看看矩阵和体力的集成方式。\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// 这很简单，对吗？\n\n// 不过，有两点需要注意。首先，这些函数在很多情况下都会用到。也许你想为一个矢量值有限元创建一个拉普拉斯或质量矩阵；或者你想使用默认的Q1映射；或者你想用拉普拉斯算子的一个系数来装配矩阵。由于这个原因，在 <code>MatrixCreator</code> 和 <code>MatrixTools</code> 命名空间中有相当多的这些函数的变种。每当你需要这些函数的一个与上面调用的略有不同的版本时，当然值得看一下文档，并检查一些东西是否适合你的需要。\n\n// 第二点是关于我们使用的正交公式：我们想对双线性形状函数进行积分，所以我们知道我们至少要使用二阶高斯正交公式。另一方面，我们希望正交规则至少有边界近似的阶数。因为有 $r$ 点的高斯规则的阶数是 $2r -1$  ，而使用 $p$ 度的多项式的边界近似的阶数是 $p+1$ ，我们知道 $2r \\geq p$  。由于r必须是一个整数，并且（如上所述）必须至少是 $2$ ，这就弥补了上述公式计算 <code>gauss_degree</code> 。\n\n// 由于对右侧向量的体力贡献的生成是如此简单，我们对边界力也要重新做一遍：分配一个合适大小的向量并调用合适的函数。边界函数有常量值，所以我们可以从库中快速生成一个对象，我们使用与上面相同的正交公式，但这次的维度较低，因为我们现在是在面上而不是在单元上积分。\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// 然后将边界的贡献与域内部的贡献相加。\n\n    system_rhs += tmp; \n\n// 在组装右手边时，我们必须使用两个不同的矢量对象，然后将它们加在一起。我们不得不这样做的原因是， <code>VectorTools::create_right_hand_side</code> 和 <code>VectorTools::create_boundary_right_hand_side</code> 函数首先清除输出向量，而不是将它们的结果与之前的内容相加。这可以合理地称为库在起步阶段的设计缺陷，但不幸的是，事情现在已经是这样了，很难改变这种无声地破坏现有代码的事情，所以我们不得不接受。\n\n// 现在，线性系统已经建立起来了，所以我们可以从矩阵和右手向量中消除我们约束到边界上其他DoF的一个自由度的均值约束，并解决这个系统。之后，再次分配约束，在这种情况下，这意味着将被约束的自由度设置为适当的值\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// 最后，评估我们得到的解决方案。正如在介绍中所说，我们对解决方案的H1半正态感兴趣。在这里，我们在库中也有一个函数可以做到这一点，尽管是以一种稍微不明显的方式： <code>VectorTools::integrate_difference</code> 函数整合了一个有限元函数和一个连续函数之间的差值的规范。因此，如果我们想要一个有限元场的规范，我们只需将连续函数设为零。请注意，这个函数，就像库中的许多其他函数一样，至少有两个版本，一个是以映射为参数的（我们在这里使用），另一个是我们在以前的例子中使用的隐含的 <code>MappingQ1</code>  。 还要注意的是，我们采用的是高一级的正交公式，以避免出现超融合效应，即在某些点上的解特别接近精确解（我们不知道这里是否会出现这种情况，但有已知的案例，我们只是想确认一下）。\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// 然后，刚刚调用的函数将其结果作为一个值的向量返回，每个值表示一个单元格上的法线。为了得到全局法线，我们要做以下工作。\n\n    const double norm = \n      VectorTools::compute_global_error(triangulation, \n                                        norm_per_cell, \n                                        VectorTools::H1_seminorm); \n\n// 最后一项任务--生成输出。\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// 下面这个解线性方程组的函数是从 step-5 中复制过来的，在那里有详细的解释。\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// 接下来，我们把解决方案以及材料ID写到一个VTU文件中。这与其他许多教程程序中的做法相似。这个教程程序中提出的新内容是，我们要确保写到文件中用于可视化的数据实际上是deal.II内部使用的数据的忠实代表。这是因为大多数可视化数据格式只用顶点坐标表示单元，但没有办法表示deal.II中使用高阶映射时的曲线边界--换句话说，你在可视化工具中看到的东西实际上不是你正在计算的东西。顺带一提，在使用高阶形状函数时也是如此。大多数可视化工具只呈现双线性/三线性的表示。这在 DataOut::build_patches().) 中有详细的讨论。\n\n// 所以我们需要确保高阶表示被写入文件中。我们需要考虑两个特别的话题。首先，我们通过 DataOutBase::VtkFlags 告诉DataOut对象，我们打算将元素的细分解释为高阶拉格朗日多项式，而不是双线性斑块的集合。最近的可视化程序，如ParaView 5.5版或更新版，然后可以呈现高阶解决方案（更多细节见<a\n//  href=\"https:github.com/dealii/dealii/wiki/Notes-on-visualizing-high-order-output\">wiki\n//  page</a>）。其次，我们需要确保映射被传递给 DataOut::build_patches() 方法。最后，DataOut类默认只打印<i>boundary</i>单元的曲面，所以我们需要确保通过映射将内部单元也打印成曲面。\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// 最后是控制要执行的不同步骤的主要函数。它的内容相当简单，生成一个圆的三角形，给它关联一个边界，然后在随后的更细的网格上做几个循环。请注意，我们将网格细化放到了循环头中；这对测试程序来说可能是件好事，但对实际应用来说，你应该考虑到这意味着网格是在循环最后一次执行后被细化的，因为增量子句（三部分循环头的最后一部分）是在比较部分（第二部分）之前执行的，如果网格已经相当细化了，这可能是相当昂贵的。在这种情况下，你应该安排代码，使网格在最后一次循环运行后不再被进一步细化（或者你应该在每次运行的开始就这样做，除了第一次）。\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// 在所有的数据生成之后，将结果的表格写到屏幕上。\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// 最后是主函数。它的结构与前面几个例子中使用的结构相同，所以可能不需要更多解释。\n\nint main() \n{ \n  try \n    { \n      std::cout.precision(5); \n\n// 这是主循环，用线性到立方的映射做计算。注意，由于我们只需要一次 <code>LaplaceProblem@<2@></code> 类型的对象，我们甚至不给它命名，而是创建一个未命名的这样的对象，并调用它的 <code>run</code> 函数，随后它又立即被销毁。\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//  main.cpp\n//  Task\n//\n//  Created by Elizabeth Lorelei on 15.11.2019.\n//  Copyright © 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": "#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": "/*\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\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// 程序以通常的包含文件开始，所有这些文件你现在应该都见过了。\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// 然后照例将这个程序的所有内容放入一个命名空间，并将deal.II命名空间导入到我们将要工作的命名空间中。我们还定义了一个标识符，以便在 <code>MMS</code> 被定义时可以运行MMS代码。否则，该程序就会解决原来的问题。\n\nnamespace BlackScholesSolver \n{ \n  using namespace dealii; \n\n#define MMS \n// @sect3{Solution Class}  \n\n// 在使用MMS进行测试时，这部分为已知的解决方案创建一个类。这里我们使用 $v(\\tau,S) = -\\tau^2 -S^2 + 6$ 作为解决方案。我们需要包括求解方程和梯度，以便进行H1半规范计算。\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// 在下面的类和函数中，我们实现了定义这个问题的右手边和边界值，为此我们需要函数对象。右手边的选择是在介绍的最后讨论的。\n\n// 首先，我们处理初始条件。\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// 接下来，我们处理左边的边界条件。\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// 然后，我们处理右边的边界条件。\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// 最后，我们处理右边的问题。\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// 下一块是这个程序的主类的声明。这与 Step-26 的教程非常相似，只是做了一些修改。必须添加新的矩阵来计算A和B矩阵，以及介绍中提到的 $V_{diff}$ 向量。我们还定义了问题中使用的参数。\n\n\n\n// -  <code>maximum_stock_price</code>  ：空间域的强加上限。这是允许的最大股票价格。\n\n// -  <code>maturity_time</code>  ：时间域的上限。这是期权到期的时间。\n\n// -  <code>asset_volatility</code>  ：股票价格的波动率。\n\n// -  <code>interest_rate</code>  : 无风险利率。\n\n// -  <code>strike_price</code>  ：买方在到期时可以选择购买股票的约定价格。\n\n// 本程序与 step-26 之间的一些细微差别是创建了 <code>a_matrix</code> and the <code>b_matrix</code>  ，这在介绍中已经说明。然后，我们还需要存储当前时间、时间步长和当前时间步长的数字。接下来，我们将把输出存储到一个 <code>DataOutStack</code> 的变量中，因为我们将把每个时间的解分层在上面，以创建解流形。然后，我们有一个变量来存储当前的周期和我们在计算解决方案时将运行的周期数。循环是给定一个网格的一个完整的解决方案计算。我们在每个周期之间细化一次网格，以展示我们程序的收敛特性。最后，我们将收敛数据存储到一个收敛表中。\n\n// 就成员函数而言，我们有一个函数可以计算每个周期的收敛信息，称为  <code>process_solution</code>  。这就像在  step-7  中所做的那样。\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// 现在，我们进入主类的实现阶段。我们将为问题中使用的各种参数设置数值。选择这些是因为它们是这些参数的相当正常的值。尽管股票价格在现实中没有上限（事实上是无限的），但我们规定了一个上限，即行权价格的两倍。两倍于行权价的选择有些武断，但它足够大，可以看到解决方案的有趣部分。\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// 下一个函数设置了DoFHandler对象，计算了约束条件，并将线性代数对象设置为正确的大小。我们还在这里通过调用库中的一个函数来计算质量矩阵。接下来我们将计算其他三个矩阵，因为这些矩阵需要 \"手工 \"计算。\n\n// 注意，时间步长在这里被初始化，因为计算时间步长需要成熟的时间。\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// 下面是创建非恒定系数的拉普拉斯矩阵的代码。这与介绍中的矩阵D相对应。这个非恒定系数在 <code>current_coefficient</code> 变量中表示。\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// 现在我们将创建A矩阵。下面是创建矩阵A的代码，在介绍中已经讨论过。非恒定系数再次用 <code>current_coefficient</code> 这个变量表示。\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// 最后我们将创建矩阵B。下面是创建矩阵B的代码，在介绍中已经讨论过。非恒定系数再次用 <code>current_coefficient</code> 这个变量表示。\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// 下一个函数是解决单个时间步长的实际线性系统的函数。这里唯一有趣的是，我们建立的矩阵是对称正定的，所以我们可以使用共轭梯度法。\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// 这是简单地将解决方案的碎片拼接起来的功能。为此，我们在每个时间段创建一个新的层，然后添加该时间段的解决方案向量。然后，该函数使用'build_patches'将其与旧的解决方案缝合在一起。\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// 对于我们所做的全局细化来说，有一个函数是有些不必要的。之所以有这个函数，是为了允许以后有可能进行适应性细化。\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// 这就是我们计算收敛和误差数据的地方，以评估程序的有效性。在这里，我们计算 $L^2$  、 $H^1$  和 $L^{\\infty}$ 的准则。\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// 接下来的部分是建立收敛和误差表。通过这个，我们需要设置如何输出在  <code>BlackScholes::process_solution</code>  期间计算的数据。首先，我们将创建标题并正确设置单元格。在这期间，我们还将规定结果的精度。然后，我们将根据  $L^2$  、  $H^1$  和  $L^{\\infty}$  规范把计算出来的误差写到控制台和错误的LaTeX文件中。\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// 接下来，我们将制作收敛表。我们将再次把它写到控制台和收敛LaTeX文件中。\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// 现在我们进入了程序的主要驱动部分。在这里我们要做的是在时间步数中循环往复，并在每次计算解向量的工作。在这里的顶部，我们设置初始细化值，然后创建一个网格。然后我们对这个网格进行一次细化。接下来，我们设置了data_out_stack对象来存储我们的解决方案。最后，我们启动一个for循环来循环处理这些循环。这让我们为每一个连续的网格细化重新计算出一个解决方案。在每次迭代开始时，我们需要重新设置时间和时间步长。我们引入一个if语句来完成这个任务，因为我们不想在第一次迭代时就这样做。\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// 接下来，我们运行主循环，该循环一直运行到超过成熟时间。我们首先计算方程的右侧，这在介绍中有所描述。回顾一下，它包含术语 $\\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}$  。我们把这些项放到变量system_rhs中，借助于一个临时向量。\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// 第二块是计算源项的贡献。这与术语  $-k_n\\left[\\frac{1}{2}F^{n-1} +\\frac{1}{2}F^n\\right]$  相对应。下面的代码调用  VectorTools::create_right_hand_side  来计算向量  $F$  ，在这里我们在评估之前设置了右侧（源）函数的时间。这一切的结果最终都在forcing_terms变量中。\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// 接下来，我们将强迫项添加到来自时间步长的强迫项中，同时建立矩阵 $\\left[\\mathbf{M}+ \\frac{1}{4}k_n\\sigma^2\\mathbf{D}+k_nr\\mathbf{M}\\right]$ ，我们必须在每个时间步长中进行反转。这些操作的最后一块是消除线性系统中悬挂的节点约束自由度。\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// 在解决这个问题之前，我们还需要做一个操作：边界值。为此，我们创建一个边界值对象，将适当的时间设置为当前时间步长的时间，并像以前多次那样对其进行评估。其结果也被用来在线性系统中设置正确的边界值。\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// 解决了这个问题，我们要做的就是求解系统，生成最后一个周期的图形数据，并创建收敛表数据。\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// 走到这一步，这个程序的主函数又没有什么好讨论的了：看起来自 step-6 以来的所有此类函数。\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": "#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 * \\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üsken. \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üsken. \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": "//==================================================================================================\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": "\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": "#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": "/*\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": "/* -*- 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 * \\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": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\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": "/*\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": "/*\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": "//---------------------------------------------------------------------------//\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": "/*\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": "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// @project        Open Space Toolkit ▸ Mathematics\n/// @file           OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Ellipsoid.cpp\n/// @author         Lucas Brémond <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": "#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": "\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": "#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": "// 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 (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’t understand it for the time being.\n */\n#define USED_ISOMETRY3D_IN_BA       0\n\n/**\n * 一次测量的值，包括一个世界坐标系下三维点与一个灰度值\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 * 从像素坐标系转换成世界坐标系\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 * 从世界坐标系转换成像素坐标系\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 * 直接法估计位姿\n * input:\n *   测量值(空间点的灰度), 新的灰度图, 相机内参;\n * output:\n *   相机位姿\n * return:\n *   true为成功, false失败\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        /* 求取分布在集中相邻４个像素点覆盖面积的像素灰度值 */\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        /* 求取分布在集中相邻４个像素点覆盖面积的像素灰度值 */\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    // 我们以第一个图像为参考，对后续图像和参考图像做直接法\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                // 去掉邻近边缘处的点\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        // 使用直接法计算相机运动\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 * 直接法估计位姿\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": "// 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                  << \"  σ = \" << 2.0/pow(1.1, sigma)\n                  << \", ℓ = \" << 1.0/pow(1.5, length)\n                  << \", ν = \" << 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": "/* \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": "// 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": "//=======================================================================\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 <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": "﻿/*! \\file hydrogen_fem.cpp\n    \\brief FEMで水素原子に対するSchrödinger方程式を解くクラスの実装\n\n    Copyright © 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 コンストラクタ\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 コンストラクタ\n\n    // #region publicメンバ関数 \n\n    double Hydrogen_FEM::do_run()\n    {\n        // 各種データの生成\n        make_data();\n\n        // 要素行列の生成\n        make_element_matrix();\n\n        // 全体行列を生成\n        make_global_matrix();\n        \n        // 境界条件処理を行う\n        boundary_conditions();\n\n        // 一般化固有値問題を解く\n        Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> es(hg_, ug_);\n\n        // エネルギー固有値を取得\n        eigenval_ = es.eigenvalues();\n\n        // 基底状態の固有関数（波動関数）（波動関数）を取得\n        phi_ = es.eigenvectors().col(0);\n\n        // 固有ベクトル（波動関数）のN要素目を追加\n        phi_.resize(NODE_TOTAL);\n\n        // 固有ベクトル（波動関数）を規格化\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            // 厳密な結果と比較\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            // 厳密な結果と比較\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メンバ関数\n\n    // #region privateメンバ関数\n\n    void Hydrogen_FEM::boundary_conditions()\n    {\n        // 左辺の全体行列のN + 1行とN + 1列を削る\n        hg_.conservativeResize(hg_.rows() - 1, hg_.cols() - 1);\n\n        // 右辺の全体行列のN + 1行とN + 1列を削る\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の添字が2以上！\");\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の添字が2以上！\");\n                return 0.0;\n            }\n\n        default:\n            BOOST_ASSERT(!\"heの添字が2以上！\");\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の添字が2以上！\");\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の添字が2以上！\");\n                return 0.0;\n            }\n\n        default:\n            BOOST_ASSERT(!\"ueの添字が2以上！\");\n            return 0.0;\n        }\n    }\n\n    void Hydrogen_FEM::make_element_matrix()\n    {\n        // 各線分要素の長さを計算\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        // 要素行列の各成分を計算\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節点のx座標を定義(R_MIN～R_MAX）\n        auto const dr = (R_MAX - R_MIN) / static_cast<double>(ELE_TOTAL);\n        for (auto i = 0; i <= ELE_TOTAL; i++) {\n            // 計算領域を等分割\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の公式によって数値積分する\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メンバ関数\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": "#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": "#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": "#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 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": "\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 <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) 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": "//==================================================================================================\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": "﻿/*! \\file scfloop.cpp\n    \\brief SCFを行うクラスの実装\n\n    Copyright ©  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 コンストラクタ\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);         // ファイルを読み込む\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 コンストラクタ\n\n    // #region publicメンバ関数\n\n    void ScfLoop::message() const\n    {\n        std::cout << pdata_->chemical_symbol_\n            << \"原子の\"\n            << pdata_->orbital_\n            << \"軌道\";\n\n        if (pdata_->eq_type_ == Data::Eq_type::DIRAC && pdata_->spin_orbital_ == Data::ALPHA) {\n            std::cout << \"、スピン上向き\";\n        }\n        else if (pdata_->eq_type_ == Data::Eq_type::DIRAC && pdata_->spin_orbital_ == Data::BETA) {\n            std::cout << \"、スピン下向き\";\n        }\n\n        std::cout << \"の波動関数と固有値を計算します。\\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メンバ関数\n\n    // #region privateメンバ関数\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(\"固有値が見つかりませんでした。終了します。\");\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(\"固有値が見つかりませんでした。終了します。\");\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が収束しませんでした。終了します。\");\n        }\n\n        return wavefunctions;\n    }\n\n    // #endregion privateメンバ関数\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//\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": "\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": "//\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/* --------------------------------------------------------------------- \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// 我们从通常的各种各样的包含文件开始，我们在以前的许多测试中都看到过。\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// 这里是仅有的三个有一些新兴趣的包含文件。第一个文件已经被使用了，例如，用于 VectorTools::interpolate_boundary_values 和 MatrixTools::apply_boundary_values 函数。然而，我们在这里使用该类中的另一个函数， VectorTools::project 来计算我们的初始值，作为连续初始值的 $L^2$ 投影。此外，我们使用  VectorTools::create_right_hand_side  来生成积分  $(f^n,\\phi^n_i)$  。这些以前总是由 <code>assemble_system</code> 或应用程序代码中的类似函数手工生成。然而，我们太懒了，不能在这里这么做，所以干脆使用库函数。\n\n#include <deal.II/numerics/vector_tools.h> \n\n// 与此非常相似，我们也懒得写代码来组装质量矩阵和拉普拉斯矩阵，尽管这只需要从以前的任何一个教程程序中复制相关代码。相反，我们想把重点放在这个程序中真正新的东西上，因此使用了 MatrixCreator::create_mass_matrix 和 MatrixCreator::create_laplace_matrix 函数。它们被声明在这里。\n\n#include <deal.II/numerics/matrix_tools.h> \n\n// 最后，这里有一个include文件，它包含了人们有时需要的各种工具函数。特别是，我们需要 Utilities::int_to_string 类，该类在给定一个整数参数后，返回它的字符串表示。它特别有用，因为它允许第二个参数，表明我们希望结果用前导零填充的数字数。我们将用它来写输出文件，其形式为 <code>solution-XXX.vtu</code> where <code>XXX</code> 表示时间步数，并且总是由三位数组成，即使我们仍然处于个位或两位数的时间步数中。\n\n#include <deal.II/base/utilities.h> \n\n// 最后一步和以前所有的程序一样。\n\nnamespace Step23 \n{ \n  using namespace dealii; \n// @sect3{The <code>WaveEquation</code> class}  \n\n// 接下来是主类的声明。它的公共函数接口与其他大多数教程程序一样。值得一提的是，我们现在必须存储四个矩阵，而不是一个：质量矩阵  $M$  ，拉普拉斯矩阵  $A$  ，用于求解  $U^n$  的矩阵  $M+k^2\\theta^2A$  ，以及用于求解  $V^n$  的带有边界条件的质量矩阵副本。请注意，在周围有一个额外的质量矩阵副本是有点浪费的。我们将在可能的改进部分讨论如何避免这种情况的策略。\n\n// 同样，我们需要 $U^n,V^n$ 的解向量，以及前一个时间步骤 $U^{n-1},V^{n-1}$ 的相应向量。 <code>system_rhs</code> 将用于我们在每个时间步骤中求解两个线性系统之一时的任何右手向量。这些将在两个函数  <code>solve_u</code>  和  <code>solve_v</code>  中解决。\n\n// 最后，变量 <code>theta</code> 用来表示参数 $\\theta$ ，该参数用于定义使用哪种时间步进方案，这在介绍中已经说明。剩下的就不言而喻了。\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// 在我们继续填写主类的细节之前，让我们定义与问题相对应的方程数据，即解 $u$ 及其时间导数 $v$ 的初始值和边界值，以及一个右手类。我们使用从Function类模板派生出来的类来做这件事，这个模板以前已经用过很多次了，所以下面的内容不应该是一个惊喜。\n\n// 我们从初始值开始，对数值 $u$ 以及它的时间导数，即速度 $v$ 都选择零。\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// 其次，我们有右手边的强制项。无聊的是，我们在这里也选择零。\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// 最后，我们有  $u$  和  $v$  的边界值。它们与介绍中描述的一样，一个是另一个的时间导数。\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// 实际逻辑的实现实际上是相当短的，因为我们把组装矩阵和右手边的向量等事情交给了库。其余的实际代码不超过130行，其中相当一部分是可以从以前的例子程序中获取的模板代码（例如，解决线性系统的函数，或生成输出的函数）。\n\n// 我们从构造函数开始（关于时间步长的选择的解释，请参见介绍中关于Courant, Friedrichs, and Lewy的部分）。\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// 下一个函数是在程序开始时，也就是在第一个时间步骤之前，设置网格、DoFHandler以及矩阵和向量。如果你已经阅读了至少到 step-6 为止的教程程序，那么前几行是相当标准的。\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// 然后，我们必须初始化程序过程中需要的3个矩阵：质量矩阵、拉普拉斯矩阵和在每个时间步长中求解 $M+k^2\\theta^2A$ 时使用的矩阵 $U^n$ 。\n\n// 在设置这些矩阵时，请注意它们都是利用了相同的稀疏模式对象。最后，在deal.II中矩阵和稀疏模式是独立对象的原因（与其他许多有限元或线性代数类不同）变得很清楚：在相当一部分应用中，我们必须持有几个恰好具有相同稀疏模式的矩阵，它们没有理由不共享这一信息，而不是重新建立并多次浪费内存。\n\n// 在初始化所有这些矩阵后，我们调用库函数来建立拉普拉斯和质量矩阵。它们所需要的只是一个DoFHandler对象和一个将用于数值积分的正交公式对象。请注意，在许多方面，这些函数比我们通常在应用程序中做的要好，例如，如果一台机器有多个处理器，它们会自动并行构建矩阵：更多信息见WorkStream的文档或 @ref threads \"多处理器并行计算 \"模块。解决线性系统的矩阵将在run()方法中被填充，因为我们需要在每个时间步长中重新应用边界条件。\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// 该函数的其余部分用于将矢量大小设置为正确的值。最后一行关闭了悬挂的节点约束对象。由于我们在一个均匀细化的网格上工作，所以不存在或没有计算过约束条件（即没有必要像其他程序那样调用 DoFTools::make_hanging_node_constraints ），但无论如何，我们需要在下面的一个地方进一步设置一个约束对象。\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// 接下来的两个函数是解决与  $U^n$  和  $V^n$  的方程有关的线性系统。这两个函数并不特别有趣，因为它们基本沿用了前面所有教程程序中的方案。\n\n// 我们可以对我们要反转的两个矩阵的预处理程序做一些小实验。然而，事实证明，对于这里的矩阵，使用雅可比或SSOR预处理器可以稍微减少解决线性系统所需的迭代次数，但由于应用预处理器的成本，在运行时间方面并不占优势。这也不是什么损失，但让我们保持简单，只做不做。\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// 同样地，下面的函数也和我们之前做的差不多。唯一值得一提的是，这里我们使用 Utilities::int_to_string 函数的第二个参数，生成了一个用前导零填充的时间步长的字符串表示，长度为3个字符。\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// 像  step-15  一样，由于我们在每个时间步长写输出（而且我们要解决的系统相对简单），我们指示DataOut使用zlib压缩算法，该算法针对速度而不是磁盘使用进行了优化，因为否则绘制输出会成为一个瓶颈。\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// 下面是程序中唯一有趣的功能。它包含了所有时间步骤的循环，但在这之前我们必须设置网格、DoFHandler和矩阵。此外，我们必须以某种方式从初始值开始。为此，我们使用 VectorTools::project 函数，该函数接收一个描述连续函数的对象，并计算该函数在DoFHandler对象所描述的有限元空间的 $L^2$ 投影。没有比这更简单的了。\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// 接下来是循环所有的时间步骤，直到我们到达结束时间（本例中为 $T=5$ ）。在每个时间步骤中，我们首先要解决 $U^n$ ，使用方程  $(M^n + k^2\\theta^2 A^n)U^n =$  。\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]$  . 请注意，我们在所有的时间步骤中使用相同的网格，因此， $M^n=M^{n,n-1}=M$  和  $A^n=A^{n,n-1}=A$  。因此，我们首先要做的是将 $MU^{n-1} - k^2\\theta(1-\\theta) AU^{n-1} + kMV^{n-1}$ 和强制项相加，并将结果放入 <code>system_rhs</code> 向量中。(对于这些加法，我们需要在循环之前声明一个临时向量，以避免在每个时间步骤中重复分配内存)。\n\n// 这里需要意识到的是我们如何将时间变量传达给描述右手边的对象：每个从函数类派生出来的对象都有一个时间字段，可以用 Function::set_time 来设置，用 Function::get_time. 来读取。 实质上，使用这种机制，所有空间和时间的函数因此被认为是在某个特定时间评估的空间的函数。这与我们在有限元程序中的典型需求非常吻合，在有限元程序中，我们几乎总是在一个时间步长上工作，而且从来没有发生过，例如，人们想在任何给定的空间位置上为所有时间评估一个时空函数。\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// 如此构建了第一个方程的右手向量后，我们要做的就是应用正确的边界值。至于右手边，这是一个在特定时间评估的时空函数，我们在边界节点插值，然后像通常那样用结果来应用边界值。然后将结果交给solve_u()函数。\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()的矩阵在每个时间步骤中都是相同的，所以人们可以认为只在模拟开始时做一次就足够了。然而，由于我们需要对线性系统应用边界值（消除了一些矩阵的行和列，并对右手边做出了贡献），在实际应用边界数据之前，我们必须在每个时间步骤中重新填充该矩阵。实际内容非常简单：它是质量矩阵和加权拉普拉斯矩阵的总和。\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// 第二步，即求解 $V^n$ ，工作原理类似，只是这次左边的矩阵是质量矩阵（我们再次复制，以便能够应用边界条件，而右边是 $MV^{n-1} - k\\left[ \\theta A U^n + (1-\\theta) AU^{n-1}\\right]$ 加上强制项。边界值的应用方式与之前相同，只是现在我们必须使用BoundaryValuesV类。\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// 最后，在计算完两个解的组成部分后，我们输出结果，计算解中的能量，并在将现在的解移入持有上一个时间步长的解的向量后，继续下一个时间步长。注意函数 SparseMatrix::matrix_norm_square 可以在一个步骤中计算 $\\left<V^n,MV^n\\right>$ 和 $\\left<U^n,AU^n\\right>$ ，为我们节省了一个临时向量和几行代码的费用。\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//剩下的就是程序的主要功能了。这里没有什么是在前面几个程序中没有展示过的。\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": "/*\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–66, 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": "// 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": "#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": "//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": "/* 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": "//\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 <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": "/*\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": "//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 * 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 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": "// [[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 * @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|                     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": "//  (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–391\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": "// 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×20 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̈bner basis. This turns out to be as simple as performing a\r\n        // Gauss-Jordan elimination on the 10×20 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×10 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×20 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>  //基于openGL的画图工具Pangolin头文件\n#include <unistd.h>             // C++中提供对操作系统访问功能的头文件，如fork/pipe/各种I/O（read/write/close等等）\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <sophus/se3.hpp>\n#include <boost/format.hpp>   // 具有格式化输出功能\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表示是任意尺寸的矩阵ixj, m(2,2)代表一个2x2的方块矩阵\n  m(0, 0) = 3;                 //代表矩阵元素a11\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;           //输出矩阵m\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 //旋转向量使用AngleAxis，运算可以当做矩阵\n    AngleAxisd rotation_vector(M_PI / 4, Vector3d(0,0,1));     //眼Z轴旋转45°\n    cout.precision(3);                                         //输出精度为小数点后两位\n    cout << \"rotation matrix = \\n\" << rotation_vector.matrix() << endl;\n    //用matrix转换成矩阵可以直接赋值\n    rotation_matrix = rotation_vector.toRotationMatrix();\n\n    //使用Amgleanxis可以进行坐标变换\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    //使用旋转矩阵\n    v_rotated = rotation_matrix * v;\n    cout << \"(1,0,0) after rotation (by matrix) = \" << v_rotated.transpose() << endl;\n\n    //欧拉角：可以将矩阵直接转换成欧拉角\n    Vector3d euler_angles = rotation_matrix.eulerAngles(2, 1, 0);       //按照ZYX顺序\n    cout << \"yaw pitch row = \"<< euler_angles.transpose() << endl;\n\n    //欧式变换矩阵使用Eigen::Isometry\n    Isometry3d T = Isometry3d::Identity();      //实质为4*4的矩阵\n    T.rotate(rotation_vector);                  //按照rotation_vector进行转化\n    T.pretranslate(Vector3d(1, 3, 4));          //平移向量设为（1， 3， 4）\n    cout << \"Transform matrix = \\n\" << T.matrix() <<endl;\n\n    //变换矩阵进行坐标变换\n    Vector3d v_transformed = T *v;\n    cout << \"v transormed =\" << v_transformed.transpose() << endl;\n\n    //四元数\n    //直接把AngleAxis赋值给四元数，反之亦然\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    //使用四元数旋转一个向量，使用重载的乘法即可\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 定义旋转矩阵与平移向量　R t\n//   // 沿Z轴转90度的旋转矩阵\n//   Eigen::Matrix3f R = Eigen::AngleAxisf(M_PI / 2, Eigen::Vector3f(0.707106781, 0, 0.707106781)).toRotationMatrix();\n//   //定义平移向量\n//   Eigen::Vector3f t(1, 0, 0); // 沿X轴平移1\n//   cout << R << endl;\n//   cout << t << endl;\n//   // SO(3) 旋转矩阵李群与李代数\n//   //旋转矩阵李群SO(3)可以由　旋转矩阵/旋转向量/四元素得到,并且都是等效的　\n//   //(注意李群的表示形式    Sophus::SO3)\n//   Sophus::SO3f SO3_R(R);                             // Sophus::SO(3)可以直接从旋转矩阵构造\n//   cout << \"SO(3) from VECTOR: \" << SO3_R.log().transpose() << endl;\n//   Sophus::SO3f SO3_V = Sophus::SO3f::rotZ(M_PI / 2); // 亦可从旋转向量构造(注意此时旋转变量的形式)\n//   cout << \"SO(3) from vector: \" << SO3_V.log().transpose() << endl;\n//   Eigen::Quaternionf q(R);                           // 或者四元数\n//   Sophus::SO3f SO3_q(q);\n//   cout << \"SO(3) from quaternion :\" << SO3_q.log().transpose() << endl;\n\n//   //旋转矩阵李代数　（李群的对数映射）\n//   //(SO(3)李代数表示形式    Eigen::Vector3d\n//   Eigen::Vector3f so3 = SO3_R.log();\n//   cout << \"so3 = \" << so3.transpose() << endl;\n//   // hat 为向量==>反对称矩阵 (李代数向量　对应的反对称矩阵)\n//   cout << \"so3 hat=\\n\"\n//        << Sophus::SO3f::hat(so3) << endl;\n//   // 相对的，vee为反对称==>向量\n//   cout << \"so3 hat vee= \" << Sophus::SO3f::vee(Sophus::SO3f::hat(so3)).transpose() << endl; // transpose纯粹是为了输出美观一些\n\n//   //旋转矩阵李代数的 增量扰动模型的更新\n//   Eigen::Vector3f update_so3(1e-4, 0, 0); //假设更新量为这么多\n//   Sophus::SO3f SO3_updated = Sophus::SO3f::exp(update_so3) * SO3_R;\n//   cout << \"SO3 updated = \" << SO3_updated.log() << endl;\n\n//   //SE(3) 变换矩阵李群与李代数\n//   //变换矩阵李群SE(3)可以由　旋转矩阵/四元素 + 平移向量得到,并且都是等效的　\n//   Sophus::SE3f SE3_Rt(R, t); // 从R,t构造SE(3)\n//   Sophus::SE3f SE3_qt(q, t); // 从q,t构造SE(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//   //变换矩阵李代数　（李群的对数映射）\n//   //(SE(3)李代数表示形式    Eigen::Matrix<double,6,1>   sophus中旋转在前，平移在后\n//   typedef Eigen::Matrix<float, 6, 1> Vector6f;\n//   Vector6f se3 = SE3_Rt.log();\n//   cout << \"se3 = \" << se3.transpose() << endl;\n//   //向量的反对称矩阵表示形式的变换\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//   //变换矩阵李代数的 增量扰动模型的更新\n//   Vector6f update_se3; //更新量\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    //读取图像\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   //在程序运行时cv::assert()计算括号内的表达式，如果表达式为FALSE (或0), 程序将报告错误，并终止执行。\n   //如果表达式不为0，则继续执行后面的语句。\n\n   //初始化\n   vector<cv::KeyPoint> keypoints_1, keypoints_2;   //关键点/角点\n   /**\n   opencv中keypoint类的默认构造函数为：\n   CV_WRAP KeyPoint() : pt(0,0), size(0), angle(-1), response(0), octave(0), class_id(-1) {}\n   pt(x,y):关键点的点坐标； // size():该关键点邻域直径大小； // angle:角度，表示关键点的方向，值为[0,360)，负值表示不使用。\n   response:响应强度，选择响应最强的关键点;   octacv:从哪一层金字塔得到的此关键点。\n   class_id:当要对图片进行分类时，用class_id对每个关键点进行区分，默认为-1。\n   **/\n   cv::Mat descriptors_1, descriptors_2;      //描述子\n   //创建ORB对象，参数为默认值\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   “Ptr<FeatureDetector> detector = ”等价于 “FeatureDetector * detector =”\n   Ptr是OpenCV中使用的智能指针模板类，可以轻松管理各种类型的指针。\n   特征检测器FeatureDetetor是虚类，通过定义FeatureDetector的对象可以使用多种特征检测及匹配方法，通过create()函数调用。\n   描述子提取器DescriptorExtractor是提取关键点的描述向量类抽象基类。\n   描述子匹配器DescriptorMatcher用于特征匹配，\"Brute-force-Hamming\"表示使用汉明距离进行匹配。\n   **/\n\n   //第一步，检测Oriented Fast角点位置\n   chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n   detector->detect(img_1, keypoints_1);     //对参数1图像进行特征的提取，并存放入参数2的数组中\n   detector->detect(img_2, keypoints_2);\n\n   //第二步，根据角点计算BREIF描述子\n   descriptor->compute(img_1, keypoints_1, descriptors_1);   //computer()计算关键点的描述子向量（注意思考参数设置的合理性）\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   //第三步， 对两幅图像中的描述子进行匹配，使用hamming距离\n   vector<cv::DMatch> matches;    //DMatch是匹配关键点描述子 类, matches用于存放匹配项\n   t1 = chrono::steady_clock::now();\n   matcher->match(descriptors_1, descriptors_2, matches); //对参数1 2的描述子进行匹配，并将匹配项存放于matches中\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   //第四步，匹配点对筛选\n   //计算最小距离和最大距离\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 可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型\n   // minmax_element()返回指向范围内最小和最大元素的一对迭代器。参数1 2为起止迭代器范围\n   // 参数3是二进制函数，该函数接受范围内的两个元素作为参数，并返回可转换为bool的值。\n   // 返回的值指示作为第一个参数传递的元素是否小于第二个。该函数不得修改其任何参数。\n   double min_dist = min_max.first->distance;  // min_max存储了一堆迭代器，first指向最小元素\n   double max_dist = min_max.second->distance; // second指向最大元素\n\n   printf(\"-- Max dist : %f \\n\", max_dist);\n   printf(\"-- Min dist : %f \\n\", min_dist);\n\n   //当描述子之间的距离大于两倍最小距离时，就认为匹配有误。但有时最小距离会非常小，所以要设置一个经验值30作为下限。\n   vector<cv::DMatch> good_matches;  //存放良好的匹配项\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   //第五步，绘制匹配结果\n   cv::Mat img_match;         //存放所有匹配点\n   cv::Mat img_goodmatch;     //存放好的匹配点\n   // drawMatches用于绘制两幅图像的匹配关键点。\n   // 参数1是第一个源图像，参数2是其关键点数组；参数3是第二张原图像，参数4是其关键点数组\n   // 参数5是两张图像的匹配关键点数组,参数6用于存放函数的绘制结果\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// 记录准确文件路径\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// 在pangolin中画图\nvoid showPointCloud(const vector<Vector4d, Eigen::aligned_allocator<Vector4d>> &pointcloud);\n\nint testEigen4()\n{\n    // 相机内参，一般为已知数据\n    double fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n    // 双目相机基线，一般已知\n    double b = 0.573;\n\n    // 读取图像\n    cv::Mat left = cv::imread(left_file, 0);   //imread()参数2为0时，表示返回灰度图像，默认值为1，代表返回彩色图像\n    cv::Mat right = cv::imread(right_file, 0); //从文件路径中读取两幅图像，返回灰度图像\n    cv::Ptr<cv::StereoSGBM> sgbm = cv::StereoSGBM::create(\n        0, 96, 9, 8 * 9 * 9, 32 * 9 * 9, 1, 63, 10, 100, 32);    // 调用OpenCv中的SGBM算法，用于计算左右图像的视差\n    cv::Mat disparity_sgbm, disparity;\n    sgbm->compute(left, right, disparity_sgbm);   //将视差的计算结果放入disparity_sgbm矩阵中\n    disparity_sgbm.convertTo(disparity, CV_32F, 1.0 / 16.0f); //将矩阵disparity_sgbm转换为括号中的格式(32位空间的单精度浮点型矩阵)\n\n    // 生成点云\n    vector<Vector4d, Eigen::aligned_allocator<Vector4d>> pointcloud; //声明一个4维的双精度浮点型可变长动态数组\n\n    // 如果自己的机器慢，可以把++v和++u改成v+=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<存储类型名称>(行，列)[通道]，用以遍历像素。省略通道部分时，可以看做二维数组简单遍历，例如M.at<uchar>(512-1,512*3-1)；\n\n            Vector4d point(0, 0, 0, left.at<uchar>(v, u) / 255.0); // 前三维为xyz,第四维为颜色。第四维数值归一化。\n\n            // 根据双目模型计算 point 的位置\n            double x = (u - cx) / fx;      //像素坐标转换为归一化坐标\n            double y = (v - cy) / fy;\n            double depth = fx * b / (disparity.at<float>(v, u));  //计算各像素点深度\n            //计算带深度信息的各点坐标\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); //输出显示disparuty，显示窗口命名为引号中的内容\n    cv::waitKey(0);           //等待关闭显示窗口，括号内参数为零则表示等待输入一个按键才会关闭，为数值则表示等待X毫秒后关闭\n    // 画出点云\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);   //创建一个Pangolin的画图窗口,声明命名以及显示的分辨率\n    glEnable(GL_DEPTH_TEST);    //启用深度缓存。\n    glEnable(GL_BLEND);         //启用gl_blend混合。Blend混合是将源色和目标色以某种方式混合生成特效的技术。\n    //混合常用来绘制透明或半透明的物体。在混合中起关键作用的α值实际上是将源色和目标色按给定比率进行混合，以达到不同程度的透明。\n    //α值为0则完全透明，α值为1则完全不透明。混合操作只能在RGBA模式下进行，颜色索引模式下无法指定α值。\n    //物体的绘制顺序会影响到OpenGL的混合处理。\n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);  //混合函数。参数1是源混合因子，参数2时目标混合因子。本命令选择了最常使用的参数。\n\n    //定义投影和初始模型视图矩阵\n    pangolin::OpenGlRenderState s_cam(\n        pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n        //对应为gluLookAt,摄像机位置,参考点位置,up vector(上向量)\n        pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n    );\n    //管理OpenGl视口的位置和大小\n    pangolin::View &d_cam = pangolin::CreateDisplay()\n        //使用混合分数/像素坐标（OpenGl视图坐标）设置视图的边界\n        .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f)\n        //指定用于接受键盘或鼠标输入的处理程序\n        .SetHandler(new pangolin::Handler3D(s_cam));\n\n    while (pangolin::ShouldQuit() == false) {\n        //清除屏幕\n        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n        //激活要渲染到视图\n        d_cam.Activate(s_cam);\n        //glClearColor：red、green、blue、alpha分别是红、绿、蓝、不透明度，值域均为[0,1]。\n        //即设置颜色，为后面的glClear做准备，默认值为（0,0,0,0）。切记：此函数仅仅设定颜色，并不执行清除工作。\n        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n        //glPointSize 函数指定栅格化点的直径。一定要在要在glBegin前,或者在画东西之前。\n        glPointSize(2);\n        //glBegin()要和glEnd()组合使用。其参数表示创建图元的类型，GL_POINTS表示把每个顶点作为一个点进行处理\n        glBegin(GL_POINTS);\n        for (auto &p: pointcloud) {\n            glColor3f(p[3], p[3], p[3]);  //在OpenGl中设置颜色\n            glVertex3d(p[0], p[1], p[2]); //设置顶点坐标\n        }\n        glEnd();\n        pangolin::FinishFrame();    //结束\n        usleep(5000);   // sleep 5 ms\n    }\n    return;\n}\n\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;  // 存放像素点坐标的数组\n\n// Camera intrinsics\ndouble fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n// baseline   双目相机基线\ndouble baseline = 0.573;\n// paths\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// 定义求雅克比的类\nclass JacobianAccumulator {\npublic:\n    // 构造函数\n    JacobianAccumulator(\n        const cv::Mat &img1_,             // 图像 1\n        const cv::Mat &img2_,             // 图像 2\n        const VecVector2d &px_ref_,       //  参考点像素坐标 数组\n        const vector<double> depth_ref_,  // 参考点深度 数组\n        Sophus::SE3d &T21_) :   // 坐标系1到坐标系2的变换矩阵\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;   // 标准互斥类型\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  双线性插值\n// 双线性内插法利用待求像素四个相邻像素的灰度在两个方向上做线性内插，在光流法求取某像素位置的灰度值时同样用到了二维线性插值。\ninline float GetPixelValue(const cv::Mat &img, float x, float y) {\n    // boundary check 边界检测\n    if (x < 0) x = 0;\n    if (y < 0) y = 0;\n    if (x >= img.cols) x = img.cols - 1;\n    if (y >= img.rows) y = img.rows - 1;\n    uchar *data = &img.data[int(y) * img.step + int(x)]; // data为指针，指向定位的像素位置\n    // step()函数，返回像素行的实际宽度\n    float xx = x - floor(x);   // floor()函数返回不大于x的最大整数\n    float yy = y - floor(y);   // xx 和 yy 就是小数部分\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///////////  主函数\nint testEigen7()\n {\n\n    cv::Mat left_img = cv::imread(left_file, 0);  // 读取灰度图像\n    cv::Mat disparity_img = cv::imread(disparity_file, 0);  // 读取视差图像\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;   // 点的数量\n    int boarder = 20;     // 边界的像素数 ，在这里表示留空边上的一部分区域，不在边上取点\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()函数返回区间内均匀分布的随机数\n        int y = rng.uniform(boarder, left_img.rows - boarder);  // don't pick pixels close to boarder\n        int disparity = disparity_img.at<uchar>(y, x);   // 像素的视差\n        double depth = fx * baseline / disparity; // 双目视觉中由视差到深度的计算\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///////  求解图像块的雅克比矩阵和增量方程\nvoid JacobianAccumulator::accumulate_jacobian(const cv::Range &range) {\n    // 求一个图像块内的雅克比矩阵的累积，为了解决单个像素在直接法中不具有代表性的缺点\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        // 计算参考点(第一幅图像)的三维坐标： ((x_i - c_x )/ fx), (y_i - c_y)/ fy, 1) * depth\n\n        // 计算当前目标点(第二幅图像)的三维坐标\n        Eigen::Vector3d point_cur = T21 * point_ref;\n\n        if (point_cur[2] < 0)   // depth invalid\n            continue;\n        // 计算第i个参考点对应的目标点的像素坐标\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        // 舍弃越界的像素点坐标\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 存放的是像素点坐标\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        // 计数共有多少个良好的目标点\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;   // 像素坐标对相机位姿李代数的一阶变化关系 : \\frac{\\partial u}{\\partial \\Delta epslon}\n                Eigen::Vector2d J_img_pixel;  // 对应位置的像素梯度 ： \\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 矩阵 ： 2*2\n                bias += -error * J;            // b 矩阵 ： - e * J (有时也写作 b = - f * J )\n                cost_tmp += error * error;     // 误差的二范数 (累加后是所有好的匹配点的误差二范数之和)\n            }\n    }\n\n    if (cnt_good) {  // 如果好的目标点不为0，也就是J和b都有计算，那么进行以下操作\n        // 计算最终的 H矩阵、b矩阵和误差二范数\n\n        unique_lock<mutex> lck(hessian_mutex);\n        // unique_lock 是为了避免 mutex 忘记释放锁。在对象创建时自动加锁，对象释放时自动解锁。\n        // std::mutex类是一个同步原语，可用于保护共享数据被同时由多个线程访问。std::mutex提供独特的，非递归的所有权语义。\n        // std::mutex是C++11中最基本的互斥量，std::mutex对象提供了独占所有权的特性，不支持递归地对std::mutex对象上锁。\n\n        H += hessian;\n        b += bias;\n        cost += cost_tmp / cnt_good; // 本图像块的像素平均误差二范数\n    }\n}\n\n//////////////// 单层直接法\nvoid DirectPoseEstimationSingleLayer(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref,\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_是opencv封装的一个多线程接口，利用这个接口可以方便实现多线程，不用考虑底层细节\n        // 下面这条语句相当于是此次迭代中的jacobian部分并行计算完了\n        cv::parallel_for_(cv::Range(0, px_ref.size()),\n                          std::bind(&JacobianAccumulator::accumulate_jacobian, &jaco_accu, std::placeholders::_1));\n                          // bind()函数起绑定效果，占位符std::placeholders::_1表示第一个参数对应jaco.accu::accumulate_jacobian的第一个参数\n        Matrix6d H = jaco_accu.hessian();\n        Vector6d b = jaco_accu.bias();\n\n        // 求解增量方程\n        Vector6d update = H.ldlt().solve(b);;\n        T21 = Sophus::SE3d::exp(update) * T21;   // 更新位姿\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///////////////// 多层直接法\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    int pyramids = 4;   // 金字塔共有4层\n    double pyramid_scale = 0.5;  // 每一层缩放比率是0.5\n    double scales[] = {1.0, 0.5, 0.25, 0.125};\n    cout << \"......1\" << endl;\n    // 创建图像金字塔\n    vector<cv::Mat> pyr1, pyr2; // image pyramids\n    for (int i = 0; i < pyramids; i++) {\n        if (i == 0) {\n            // 第一层，底层是原图像\n            pyr1.push_back(img1);\n            pyr2.push_back(img2);\n        } else {\n            // 上面的层使用resize()函数进行创建\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    // 由粗至精进行求解\n    for (int level = pyramids - 1; level >= 0; level--) {\n        VecVector2d px_ref_pyr; // 存放该层的目标点\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        // 不同的层上面由于进行了缩放，相机内参也相应的进行了改变\n        fx = fxG * scales[level];\n        fy = fyG * scales[level];\n        cx = cxG * scales[level];\n        cy = cyG * scales[level];\n        // 调用单层直接法进行求解\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": "#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// 整数 --- 数値\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": "#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": "/**\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": "// 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 “Global Structure-from-Motion by Similarity Averaging\"\n/// Zhaopeng Cui and Ping Tan. (ICCV 2015).”\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": "//#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 *  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": "//#########################################################//\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": "/*******************************************************************************\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": "#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": "#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 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": "\n//此源码被清华学神尹成大魔王专业翻译分析并修改\n//尹成QQ77025077\n//尹成微信18510341407\n//尹成所在QQ群721929980\n//尹成邮箱 yinc13@mails.tsinghua.edu.cn\n//尹成毕业于清华大学,微软区块链领域全球最有价值专家\n//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620\n//————————————————————————————————————————————————————————————————————————————————————————————————————————————————\n/*\n    此文件是Rippled的一部分：https://github.com/ripple/rippled\n    版权所有（c）2012-2015 Ripple Labs Inc.\n\n    使用、复制、修改和/或分发本软件的权限\n    特此授予免费或不收费的目的，前提是\n    版权声明和本许可声明出现在所有副本中。\n\n    本软件按“原样”提供，作者不作任何保证。\n    关于本软件，包括\n    适销性和适用性。在任何情况下，作者都不对\n    任何特殊、直接、间接或后果性损害或任何损害\n    因使用、数据或利润损失而导致的任何情况，无论是在\n    合同行为、疏忽或其他侵权行为\n    或与本软件的使用或性能有关。\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} //涟漪\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": "#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 * 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 \"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": "\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_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": "\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// 前面几个包括的内容和前面的程序一样，所以不需要额外的注释。\n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n\n// 然而，下一个文件是新的。我们需要这个包含文件来将自由度（DoF）与顶点、直线和单元联系起来。\n\n#include <deal.II/dofs/dof_handler.h> \n\n// 以下文件包含了对双线性有限元的描述，包括它在三角形的每个顶点上有一个自由度，但在面和单元内部没有自由度。\n\n// (事实上，该文件包含了对拉格朗日元素的一般描述，即还有二次、三次等版本，而且不仅是2d，还有1d和3d。)\n\n#include <deal.II/fe/fe_q.h> \n\n// 在下面的文件中，可以找到几个操作自由度的工具。\n\n#include <deal.II/dofs/dof_tools.h> \n\n// 我们将使用一个稀疏矩阵来可视化自由度在网格上的分布所产生的非零条目模式。这个类可以在这里找到。\n\n#include <deal.II/lac/sparse_matrix.h> \n\n// 我们还需要使用一个中间的稀疏模式结构，可以在这个文件中找到。\n\n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n\n// 我们希望使用一种特殊的算法来重新计算自由度。它被声明在这里。\n\n#include <deal.II/dofs/dof_renumbering.h> \n\n// 而这又是C++输出所需要的。\n\n#include <fstream> \n\n// 最后，和 step-1 一样，我们将deal.II命名空间导入到全局范围。\n\nusing namespace dealii; \n// @sect3{Mesh generation}  \n\n// 这就是前面 step-1 例子程序中产生圆形网格的函数，细化步骤较少。唯一不同的是，它通过其参数返回它所产生的网格。\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// 到目前为止，我们只有一个网格，即一些几何信息（顶点的位置）和一些拓扑信息（顶点如何与线相连，线与单元格相连，以及哪些单元格与哪些其他单元格相邻）。要使用数值算法，还需要一些逻辑信息：我们希望将自由度数字与每个顶点（或线，或单元，如果我们使用高阶元素的话）联系起来，以便以后生成描述三角形上有限元场的矩阵和矢量。\n\n// 这个函数显示了如何做到这一点。要考虑的对象是 <code>DoFHandler</code> 类模板。 然而，在这之前，我们首先需要一些东西来描述这些对象中的每一个要与多少个自由度相关联。由于这是有限元空间定义的一个方面，有限元基类存储了这个信息。在目前的情况下，我们因此创建了一个描述拉格朗日元素的派生类 <code>FE_Q</code> 的对象。它的构造函数需要一个参数，说明元素的多项式程度，这里是1（表示一个双线性元素）；这就对应于每个顶点的一个自由度，而线和四边形内部没有自由度。如果给构造函数的值是3，我们就会得到一个双立方体元素，每个顶点有一个自由度，每条线有两个自由度，单元内有四个自由度。一般来说， <code>FE_Q</code> 表示具有完整多项式（即张量积多项式）的连续元素家族，直到指定的顺序。\n\n// 我们首先需要创建一个这个类的对象，然后把它传递给 <code>DoFHandler</code> 对象，为自由度分配存储空间（用deal.II的行话说：我们<i>distribute degrees of freedom</i>）。\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// 现在我们已经将自由度与每个顶点的全局数字联系起来，我们想知道如何将其可视化？ 没有简单的方法可以直接将与每个顶点相关的自由度数字可视化。然而，这样的信息几乎不会真正重要，因为编号本身或多或少是任意的。还有更重要的因素，我们将在下文中展示其中一个。\n\n// 与三角形的每个顶点相关的是一个形状函数。假设我们想解决类似拉普拉斯方程的问题，那么不同的矩阵条目将是每对这样的形状函数的梯度的积分。显然，由于形状函数只在与它们相关的顶点相邻的单元格上是非零的，所以只有当与该列和行%号相关的形状函数的支持相交时，矩阵条目才是非零的。这只是相邻形状函数的情况，因此也只是相邻顶点的情况。现在，由于顶点被上述函数 (DoFHandler::distribute_dofs), 或多或少地随机编号，矩阵中非零项的模式将有些参差不齐，我们现在就来看看它。\n\n// 首先，我们要创建一个结构，用来存储非零元素的位置。然后，这个结构可以被一个或多个稀疏矩阵对象使用，这些对象在这个稀疏模式所存储的位置上存储条目的值。存储这些位置的类是SparsityPattern类。然而，事实证明，当我们试图立即填充这个类时，它有一些缺点：它的数据结构的设置方式是，我们需要对我们可能希望在每一行的最大条目数有一个估计。在两个空间维度上，通过 DoFHandler::max_couplings_between_dofs() 函数可以得到合理的估计值，但是在三个维度上，该函数几乎总是严重高估真实的数字，导致大量的内存浪费，有时对于所使用的机器来说太多，即使未使用的内存可以在计算稀疏模式后立即释放。为了避免这种情况，我们使用了一个中间对象DynamicSparsityPattern，该对象使用了一个不同的%内部数据结构，我们可以随后将其复制到SparsityPattern对象中，而不需要太多的开销。关于这些数据结构的一些更多信息可以在 @ref Sparsity 模块中找到）。为了初始化这个中间数据结构，我们必须给它提供矩阵的大小，在我们的例子中，矩阵是正方形的，行和列的数量与网格上的自由度相同。\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// 现在我们已经准备好创建实际的稀疏模式了，以后我们可以用在我们的矩阵上。它将包含已经在DynamicSparsityPattern中集合的数据。\n\n  SparsityPattern sparsity_pattern; \n  sparsity_pattern.copy_from(dynamic_sparsity_pattern); \n\n// 有了这个，我们现在可以把结果写到一个文件里。\n\n  std::ofstream out(\"sparsity_pattern1.svg\"); \n  sparsity_pattern.print_svg(out); \n\n// 结果被存储在一个 <code>.svg</code> 文件中，矩阵中的每个非零条目都对应于图像中的一个红色方块。输出结果将显示如下。\n\n// 如果你看一下，你会注意到稀疏性模式是对称的。这不应该是一个惊喜，因为我们没有给 <code>DoFTools::make_sparsity_pattern</code> 任何信息，表明我们的双线性形式可能以非对称的方式耦合形状函数。你还会注意到它有几个明显的区域，这源于编号从最粗的单元开始，然后到较细的单元；由于它们都是围绕原点对称分布的，这在稀疏模式中再次显示出来。\n\n} \n// @sect3{Renumbering of DoFs}  \n\n// 在上面产生的稀疏模式中，非零条目在对角线上延伸得很远。对于某些算法来说，例如不完全LU分解或Gauss-Seidel预处理，这是不利的，我们将展示一个简单的方法来改善这种情况。\n\n// 请记住，为了使矩阵中的一个条目 $(i,j)$ 不为零，形状函数i和j的支持需要相交（否则在积分中，积分将到处为零，因为在某个点上，一个或另一个形状函数为零）。然而，形状函数的支撑点只有在彼此相邻的情况下才会相交，所以为了使非零条目聚集在对角线周围（其中 $i$ 等于 $j$ ），我们希望相邻的形状函数的索引（DoF编号）相差不大。\n\n// 这可以通过一个简单的前行算法来实现，即从一个给定的顶点开始，给它的索引为0。然后，依次对其邻居进行编号，使其指数接近于原始指数。然后，他们的邻居，如果还没有被编号，也被编号，以此类推。\n\n// 有一种算法沿着这些思路增加了一点复杂性，那就是Cuthill和McKee的算法。我们将在下面的函数中使用它来对自由度进行重新编号，从而使产生的稀疏模式在对角线周围更加本地化。该函数唯一有趣的部分是对 <code>DoFRenumbering::Cuthill_McKee</code> 的第一次调用，其余部分基本上与以前一样。\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// 再次，输出如下。请注意，非零项在对角线附近的聚类情况要比以前好得多。这种效果对于较大的矩阵来说更加明显（目前的矩阵有1260行和列，但是大的矩阵往往有几十万行）。\n\n// 值得注意的是， <code>DoFRenumbering</code> 类也提供了一些其他的算法来重新编号自由度。例如，如果所有的耦合都在矩阵的下三角或上三角部分，那当然是最理想的，因为这样的话，解决线性系统就只需要向前或向后替换。当然，这对于对称稀疏模式来说是无法实现的，但在一些涉及传输方程的特殊情况下，通过列举从流入边界沿流线到流出边界的自由度，这是可能的。毫不奇怪， <code>DoFRenumbering</code> 也有这方面的算法。\n\n//  @sect3{The main function}  \n\n// 最后，这是主程序。它所做的唯一一件事就是分配和创建三角形，然后创建一个 <code>DoFHandler</code> 对象并将其与三角形相关联，最后对其调用上述两个函数。\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": "#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 <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": "// 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 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": "/**\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": "#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–256, 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 <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// 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": "#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 <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: 此处你需要计算每个像素下cubemap某个面的球谐系数\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: 此处你需要计算给定方向下的unshadowed传输项球谐函数值\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: 此处你需要计算给定方向下的shadowed传输项球谐函数值\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: 在完成了球谐系数计算后，你需要删除下列四行，这四行代码的作用是用来可视化模型法线\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": "// 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": "/*\n* Copyright 2019 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés\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": "/* -*- 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// 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": "// $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 \"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": "#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 (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": "// 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": "\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// 由于这个程序只是对 step-4 的改编，所以在头文件方面没有太多的新东西。在deal.II中，我们通常按照base-lac-grid-dofs-fe-numerics的顺序列出包含文件，然后是C++标准包含文件。\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// 唯一值得关注的两个新头文件是LinearOperator和PackagedOperation类的文件。\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// 这是唯一重要的新标题，即声明Raviart-Thomas有限元的标题。\n\n#include <deal.II/fe/fe_raviart_thomas.h> \n\n// 最后，作为本程序中的一项奖励，我们将使用一个张量系数。由于它可能具有空间依赖性，我们认为它是一个张量值的函数。下面的include文件提供了 <code>TensorFunction</code> 类，提供了这样的功能。\n\n#include <deal.II/base/tensor_function.h> \n\n// 最后一步和以前所有的程序一样。我们把所有与这个程序相关的代码放到一个命名空间中。(这个想法在  step-7  中首次提出) 。\n\nnamespace Step20 \n{ \n  using namespace dealii; \n// @sect3{The <code>MixedLaplaceProblem</code> class template}  \n\n// 同样，由于这是对 step-6 的改编，主类与该教程程序中的主类几乎相同。就成员函数而言，主要区别在于构造函数将Raviart-Thomas元素的度数作为参数（并且有一个相应的成员变量来存储这个值），并且增加了 <code>compute_error</code> 函数，在这个函数中，不出意外，我们将计算精确解和数值解之间的差异，以确定我们计算的收敛性。\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// 第二个区别是疏散模式、系统矩阵、解和右手向量现在被封锁了。这意味着什么，人们可以用这些对象做什么，在本程序的介绍中已经解释过了，下面我们在解释这个问题的线性求解器和预处理器时也会进一步解释。\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// 我们的下一个任务是定义我们问题的右手边（即原始拉普拉斯方程中压力的标量右手边），压力的边界值，以及一个描述压力和精确解的速度的函数，以便以后计算误差。请注意，这些函数分别有一个、一个和 <code>dim+1</code> 个分量，我们将分量的数量传递给 <code>Function@<dim@></code> 基类。对于精确解，我们只声明实际一次性返回整个解向量（即其中的所有成分）的函数。下面是各自的声明。\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// 然后我们还必须定义这些各自的函数，当然了。鉴于我们在介绍中讨论了解决方案应该是怎样的，下面的计算应该是很简单的。\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// 除了其他方程数据外，我们还想使用渗透性张量，或者更好的是--因为这是在弱形式中出现的全部内容--渗透性张量的逆，  <code>KInverse</code>  。对于验证解的精确性和确定收敛顺序的目的来说，这个张量的作用大于帮助。因此，我们将简单地把它设置为同一矩阵。\n\n// 然而，在现实生活中的多孔介质流动模拟中，空间变化的渗透率张量是不可缺少的，我们想利用这个机会来展示使用张量值函数的技术。\n\n// 可能不足为奇，deal.II也有一个基类，不仅适用于标量和一般的矢量值函数（ <code>Function</code> 基类），也适用于返回固定维度和等级的张量的函数， <code>TensorFunction</code> 模板。在这里，所考虑的函数返回一个dim-by-dim矩阵，即一个等级为2、维度为 <code>dim</code> 的张量。然后我们适当地选择基类的模板参数。\n\n//  <code>TensorFunction</code> 类提供的接口本质上等同于 <code>Function</code> 类。特别是，存在一个 <code>value_list</code> 函数，它接收一个评估函数的点的列表，并在第二个参数中返回函数的值，一个张量的列表。\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// 实现起来就不那么有趣了。和以前的例子一样，我们在类的开头添加一个检查，以确保输入和输出参数的大小是相同的（关于这个技术的讨论见 step-5 ）。然后我们在所有的评估点上循环，对于每一个评估点，将输出张量设置为身份矩阵。\n\n// 在函数的顶部有一个奇怪的地方（`(void)point;`语句），值得讨论。我们放到输出`values`数组中的值实际上并不取决于函数被评估的坐标`points`数组。换句话说，`points'参数实际上是不用的，如果我们想的话，可以不给它起名字。但是我们想用`points`对象来检查`values`对象是否有正确的大小。问题是，在发布模式下，`AssertDimension`被定义为一个宏，扩展为空；然后编译器会抱怨`points`对象没有使用。消除这个警告的习惯方法是有一个评估（读取）变量的语句，但实际上不做任何事情：这就是`(void)points;`所做的：它从`points`中读取，然后将读取的结果转换为`void`，也就是什么都没有。换句话说，这句话是完全没有意义的，除了向编译器解释是的，这个变量事实上是被使用的，即使是在发布模式下。(在调试模式下，`AssertDimension`宏会扩展为从变量中读出的东西，所以在调试模式下，这个有趣的语句是没有必要的)。\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// 在这个类的构造函数中，我们首先存储传入的关于我们将使用的有限元的度数的值（例如，度数为0，意味着使用RT(0)和DG(0)），然后构造属于介绍中描述的空间 $X_h$ 的向量值的元素。构造函数的其余部分与早期的教程程序一样。\n\n// 这里唯一值得描述的是，这个变量所属的 <code>fe</code> variable. The <code>FESystem</code> 类的构造函数调用有很多不同的构造函数，它们都是指将较简单的元素绑定在一起，成为一个较大的元素。在目前的情况下，我们想把一个RT(度)元素与一个DQ(度)元素结合起来。这样做的 <code>FESystem</code> 构造函数要求我们首先指定第一个基本元素（给定程度的 <code>FE_RaviartThomas</code> 对象），然后指定这个基本元素的副本数量，然后类似地指定 <code>FE_DGQ</code> 元素的种类和数量。注意Raviart-Thomas元素已经有 <code>dim</code> 个矢量分量，所以耦合元素将有 <code>dim+1</code> 个矢量分量，其中第一个 <code>dim</code> 个对应于速度变量，最后一个对应于压力。\n\n// 我们从基本元素中构建这个元素的方式与我们在 step-8 中的方式也值得比较：在那里，我们将其构建为 <code>fe (FE_Q@<dim@>(1), dim)</code> ，即我们简单地使用 <code>dim</code> copies of the <code>FE_Q(1)</code> 元素，每个坐标方向上的位移都有一份。\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// 接下来的函数开始于众所周知的函数调用，创建和细化一个网格，然后将自由度与之关联。\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// 然而，接下来事情就变得不同了。正如介绍中提到的，我们要将矩阵细分为对应于速度和压力这两种不同的变量的块。为此，我们首先要确保与速度和压力相对应的指数不会混在一起。首先是所有速度自由度，然后是所有压力自由度。这样一来，全局矩阵就很好地分离成一个 $2 \\times 2$ 系统。为了达到这个目的，我们必须根据自由度的矢量分量对其重新编号，这个操作已经很方便地实现了。\n\n    DoFRenumbering::component_wise(dof_handler); \n\n// 接下来，我们要弄清楚这些块的大小，以便我们可以分配适当的空间量。为此，我们调用了 DoFTools::count_dofs_per_fe_component() 函数，该函数计算了某个向量分量的形状函数非零的数量。我们有 <code>dim+1</code> 个向量分量， DoFTools::count_dofs_per_fe_component() 将计算有多少个形状函数属于这些分量中的每个。\n\n// 这里有一个问题。正如该函数的文档所描述的，它 <i>wants</i> 将  $x$  -速度形状函数的数量放入  <code>dofs_per_component[0]</code>  中，将  $y$  -速度形状函数的数量放入  <code>dofs_per_component[1]</code>  中（以及类似的3d），并将压力形状函数的数量放入  <code>dofs_per_component[dim]</code>  中 。但是，Raviart-Thomas元素的特殊性在于它是非 @ref GlossPrimitive \"原始 \"的，也就是说，对于Raviart-Thomas元素，所有的速度形状函数在所有分量中都是非零。换句话说，该函数不能区分 $x$ 和 $y$ 速度函数，因为<i>is</i>没有这种区分。因此，它将速度的总体数量放入 <code>dofs_per_component[c]</code>  ,  $0\\le c\\le \\text{dim}$ 中的每一个。另一方面，压力变量的数量等于在dim-th分量中不为零的形状函数的数量。\n\n// 利用这些知识，我们可以从 <code>dofs_per_component</code> 的第一个 <code>dim</code> 元素中的任何一个得到速度形状函数的数量，然后用下面这个来初始化向量和矩阵块的大小，以及创建输出。\n\n//  @note  如果你觉得这个概念难以理解，你可以考虑用函数  DoFTools::count_dofs_per_fe_block()  来代替，就像我们在  step-22  的相应代码中做的那样。你可能还想阅读一下术语表中 @ref GlossBlock \"块 \"和 @ref GlossComponent \"组件 \"的区别。\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// 下一个任务是为我们将要创建的矩阵分配一个稀疏模式。我们使用与前面步骤一样的压缩稀疏模式，但是由于 <code>system_matrix</code> 是一个块状矩阵，我们使用 <code>BlockDynamicSparsityPattern</code> 类，而不仅仅是 <code>DynamicSparsityPattern</code>  。这种块状稀疏模式在 $2 \\times 2$ 模式下有四个块。块的大小取决于 <code>n_u</code> and <code>n_p</code> ，它持有速度和压力变量的数量。在第二步中，我们必须指示块系统更新它所管理的块的大小的知识；这发生在 <code>dsp.collect_sizes ()</code> 的调用中。\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// 我们以与非区块版本相同的方式使用压缩的区块稀疏模式，以创建稀疏模式，然后创建系统矩阵。\n\n    sparsity_pattern.copy_from(dsp); \n    system_matrix.reinit(sparsity_pattern); \n\n// 然后，我们必须以与块压缩稀疏度模式完全相同的方式调整解决方案和右侧向量的大小。\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// 同样地，组装线性系统的函数在这个例子的介绍中已经讨论过很多了。在它的顶部，发生的是所有常见的步骤，此外，我们不仅为单元项分配正交和 <code>FEValues</code> 对象，而且还为面项分配。之后，我们为变量定义通常的缩写，并为本地矩阵和右手贡献分配空间，以及保存当前单元的全局自由度数的数组。\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// 下一步是声明代表方程中源项、压力边界值和系数的对象。除了这些代表连续函数的对象外，我们还需要数组来保存它们在各个单元格（或面，对于边界值）的正交点的值。请注意，在系数的情况下，数组必须是矩阵的一种。\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// 最后，我们需要几个提取器，用来获取矢量值形状函数的速度和压力成分。它们的功能和使用在 @ref vector_valued报告中有详细描述。基本上，我们将把它们作为下面FEValues对象的下标：FEValues对象描述了形状函数的所有矢量分量，而在订阅后，它将只指速度（一组从零分量开始的 <code>dim</code> 分量）或压力（位于 <code>dim</code> 位置的标量分量）。\n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure(dim); \n\n// 有了这些，我们就可以继续对所有单元进行循环。这个循环的主体已经在介绍中讨论过了，这里就不再做任何评论了。\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// 循环所有单元的最后一步是将局部贡献转移到全局矩阵和右手向量中。请注意，我们使用的接口与之前的例子完全相同，尽管我们现在使用的是块状矩阵和向量，而不是常规的。换句话说，对于外界来说，块对象具有与矩阵和向量相同的接口，但它们还允许访问单个块。\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// 我们在这个例子中使用的线性求解器和预处理器已经在介绍中进行了详细的讨论。因此，我们在这里不再讨论我们的方法的原理，而只是对剩下的一些实现方面进行评论。\n\n//  @sect4{MixedLaplace::solve}  \n\n// 正如在介绍中所概述的那样，求解函数基本上由两个步骤组成。首先，我们必须形成涉及舒尔补数的第一个方程，并求解压力（解决方案的第一部分）。然后，我们可以从第二个方程（解的第0部分）中重构速度。\n\n  template <int dim> \n  void MixedLaplaceProblem<dim>::solve() \n  { \n\n// 作为第一步，我们声明对矩阵的所有块状成分、右手边和我们将需要的解向量的引用。\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// 然后，我们将创建相应的LinearOperator对象并创建 <code>op_M_inv</code> 运算器。\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// 这样我们就可以声明舒尔补数  <code>op_S</code>  和近似舒尔补数  <code>op_aS</code>  。\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// 我们现在从 <code>op_aS</code> 中创建一个预处理程序，应用固定数量的30次（便宜的）CG迭代。\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// 现在来看看第一个方程。它的右边是 $B^TM^{-1}F-G$  ，这就是我们在前几行计算的结果。然后我们用CG求解器和我们刚刚声明的预处理程序来解决第一个方程。\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// 得到压力后，我们可以计算速度。方程为 $MU=-BP+F$  ，我们通过首先计算右手边，然后与代表质量矩阵逆的对象相乘来解决这个问题。\n\n    U = op_M_inv * (F - op_B * P); \n  } \n// @sect3{MixedLaplaceProblem class implementation (continued)}  \n// @sect4{MixedLaplace::compute_errors}  \n\n// 在我们处理完线性求解器和预处理器之后，我们继续实现我们的主类。特别是，下一个任务是计算我们数值解的误差，包括压力和速度。\n\n// 为了计算解的误差，我们已经在  step-7  和  step-11  中介绍了  <code>VectorTools::integrate_difference</code>  函数。然而，在那里我们只处理了标量解，而在这里我们有一个矢量值的解，其组成部分甚至表示不同的量，并且可能有不同的收敛阶数（由于所使用的有限元的选择，这里不是这种情况，但在混合有限元应用中经常出现这种情况）。因此，我们要做的是 \"掩盖 \"我们感兴趣的成分。这很容易做到： <code>VectorTools::integrate_difference</code> 函数将一个指向权重函数的指针作为其参数之一（该参数默认为空指针，意味着单位权重）。我们要做的是传递一个函数对象，在我们感兴趣的成分中等于1，而在其他成分中等于0。例如，为了计算压力误差，我们应该传入一个函数，该函数在分量 <code>dim</code> 中代表单位值的常数向量，而对于速度，常数向量在第一个 <code>dim</code> 分量中应该是1，而在压力的位置是0。\n\n// 在deal.II中， <code>ComponentSelectFunction</code> 正是这样做的：它想知道它要表示的函数应该有多少个向量分量（在我们的例子中，这将是 <code>dim+1</code> ，用于联合速度-压力空间），哪个个体或范围的分量应该等于1。因此，我们在函数的开头定义了两个这样的掩码，接下来是一个代表精确解的对象和一个向量，我们将在其中存储由 <code>integrate_difference</code> 计算的单元误差。\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// 正如在 step-7 中已经讨论过的那样，我们必须认识到，不可能精确地整合误差。我们所能做的就是用正交法对这个积分进行近似。这实际上在这里提出了一个小小的转折：如果我们像人们可能倾向于做的那样天真地选择一个 <code>QGauss@<dim@>(degree+1)</code> 类型的对象（这就是我们用于积分线性系统的对象），就会发现误差非常小，根本不遵循预期的收敛曲线。现在的情况是，对于这里使用的混合有限元，高斯点恰好是超收敛点，其中的点误差要比其他地方小得多（而且收敛的阶数更高）。因此，这些点不是特别好的积分点。为了避免这个问题，我们只需使用梯形法则，并在每个坐标方向上迭代 <code>degree+2</code> 次（同样如 step-7 中的解释）。\n\n    QTrapezoid<1>  q_trapez; \n    QIterated<dim> quadrature(q_trapez, degree + 2); \n\n// 有了这个，我们就可以让库计算出误差并将其输出到屏幕上。\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// 最后一个有趣的函数是我们生成图形输出的函数。请注意，所有的速度分量都得到相同的解名 \"u\"。再加上使用 DataComponentInterpretation::component_is_part_of_vector ，这将导致 DataOut<dim>::write_vtu() 生成各个速度分量的矢量表示，更多信息请参见 step-22 或 @ref VVOutput 模块中的 \"生成图形输出 \"部分。最后，对于高阶元素来说，在图形输出中每个单元只显示一个双线性四边形似乎不合适。因此，我们生成大小为(度数+1)x(度数+1)的斑块来捕捉解决方案的全部信息内容。有关这方面的更多信息，请参见 step-7 的教程程序。\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// 这是我们主类的最后一个函数。它唯一的工作是按照自然顺序调用其他函数。\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// 我们从  step-6  而不是  step-4  那里偷来的主函数。它几乎等同于 step-6 中的函数（当然，除了改变的类名），唯一的例外是我们将有限元空间的度数传递给混合拉普拉斯问题的构造函数（这里，我们使用零阶元素）。\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� 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� 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 <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": "//==================================================================================================\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": "/**\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, “A multi-state constraint kalman filter\n// \"for vision-aided inertial navigation,” in Proc. IEEE Int. Conf. on Robotics\n// and Automation, pp. 10–14, 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": "#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;         //无人机参考位置\n\nmavros_msgs::State current_state;           //无人机当前状态(mode arm)\nsensor_msgs::Imu   imu_drone;               //读入的无人机的IMU信息 包括姿态角和线加速度\n\ngeometry_msgs::PoseStamped  pos_drone;      //读入的无人机当前位置\ngeometry_msgs::PoseStamped  pos_drone_last; //读入的无人机上一次位置\ngeometry_msgs::PoseStamped  fused_drone; //融合了vicon数据的无人机位姿，注意是NED坐标下的，需要翻转\n\ngeometry_msgs::TwistStamped vel_drone;      //读入的无人机当前速度\n\ngeometry_msgs::Vector3 acc_receive;         //读入的无人机线加速度\ngeometry_msgs::Vector3 angle_receive;       //读入的无人机姿态（欧拉角）\ngeometry_msgs::Vector3 angle_fromvicon;       //读入的vicon计算的sgement姿态（欧拉角）\ngeometry_msgs::Vector3 angle_fromvicon_qua;       //读入的vicon计算的sgement姿态（欧拉角）\ngeometry_msgs::Vector3 angle_fromviconinit;  //读入的vicon计算的sgement initial 姿态（欧拉角）\ngeometry_msgs::Vector3 fusedangle_receive;\n\ngeometry_msgs::Quaternion orientation_target;   //发给无人机的姿态指令\n\ngeometry_msgs::Vector3 angle_des;            //线性模型输出的理想值\n//geometry_msgs::Vector3 angle_dis;            //DOB控制器估计的扰动值\ngeometry_msgs::Vector3 angle_target;            //经DOB控制器作用后的实际系统输入值\ngeometry_msgs::Vector3 vel_target, vel_read, vel_read2;\ngeometry_msgs::Vector3 currentRPYangle;   //欧拉角\ngeometry_msgs::Vector3 filteredPlaneVelmsg;   //欧拉角\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){ //由ConstPtr可以看到msg是指针的引用，因此*msg相当于对被引用的指针对象取值\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 仿真数据\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); //车的pos+twist\n    ros::Subscriber plane_velocity_sub = nh.subscribe<geometry_msgs::TwistStamped>(\"mavros/local_position/velocity_local\", 10, plane_vel_cb); //twist\n\n    // 【发布】飞机姿态/拉力信息 坐标系:NED系\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": "#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": "#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": "#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": "/* =========================================================================\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>     // 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": "#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": "/*\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": "/**\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 <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": "/*\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 <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": "///////////////////////////////////////////////////////////////////////////////\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#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": "#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": "#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 <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": "/* 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": "/**\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": "/******************************************************************************\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 //逆向组合法进行2D图像对齐,这个好像是在LK十年那个论文里有说过\n //输入右相机的图像,从左相机变换到右相机上的patch_border,从左相机变换到右相机上的patch,最大迭代次数\n //输出最终块匹配残差最小的右目中特征点的像素坐标\n //残差: r = I(p_cur) - I(p_ref) + m ,其中I(*)表示在某个像素位置的光度, m是均值差.cur是右相机,ref是左相机\n //优化变量是p_ref,m，这里为什么是p_ref而不是p_cur,是因为如果用p_cur，每次增量以后还需要再计算一次这个的J,用p_ref只用算一次,均值差也做为优化变量是防止噪声\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// 模板图像对像素 x,y 坐标进行求导\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框边长\n     // 图像导数的指针\n  float* it_dx = ref_patch_dx;\n  float* it_dy = ref_patch_dy;\n  //构造H矩阵\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像素值关于位置，其实就是梯度\n      J[0] = 0.5 * (it[1] - it[-1]);\n      J[1] = 0.5 * (it[ref_step] - it[-ref_step]);\n      J[2] = 1;//均值差的导数\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     //初值\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; update.setZero();//优化变量的增量\n  for (int iter = 0; iter < n_iter; ++iter) //优化开始\n  {\n    int u_r = floor(u);\n    int v_r = floor(v);\n    //边缘处跳过\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    //双线性插值I(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) 以算出这个特征点在右目图像中的像素值\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;// 左图像 patch指针\n    float* it_ref_dx = ref_patch_dx; // 左图像 patch x方向导数指针\n    float* it_ref_dy = ref_patch_dy;// 左图像 patch y方向导数指针\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          //残差r = 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];//双线性插值得到curimg中的像素值\n        float res = search_pixel - *it_ref + mean_diff;\n        //计算 H * deltax = -Jr中的Jres\n        Jres[0] -= res*(*it_ref_dx);\n        Jres[1] -= res*(*it_ref_dy);\n        Jres[2] -= res;\n        new_chi2 += res*res;// 卡方\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    //更新变量\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        //满足收敛条件\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 * 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": "#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 © 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 © 2016-2017年 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 <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// 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": "#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": "#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": "// #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": "#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": "/*\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": "//\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\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// 线性代数的包含文件。一个普通的SparseMatrix，它又将包括SparsityPattern和Vector类的必要文件。\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// 包括用于设置网格的文件\n\n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_refinement.h> \n\n// FiniteElement类和DoFHandler的包含文件。\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// 使用MeshWorker框架的包含文件\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// 与拉普拉斯相关的局部积分器的包含文件\n\n#include <deal.II/integrators/laplace.h> \n\n// 支持多网格方法\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// 最后，我们从库中取出我们的精确解，以及正交和附加工具。\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库的所有类都在dealii命名空间中。为了节省打字，我们告诉编译器也要在其中搜索名字。\n\nnamespace Step39 \n{ \n  using namespace dealii; \n\n// 这是我们用来设置边界值的函数，也是我们比较的精确解。\n\n  Functions::SlitSingularityFunction<2> exact_solution; \n// @sect3{The local integrators}  \n\n// MeshWorker将局部积分与单元格和面的循环分离开来。因此，我们必须编写局部积分类来生成矩阵、右手边和误差估计器。\n\n// 所有这些类都有相同的三个函数，分别用于对单元、边界面和内部面的积分。局部积分所需的所有信息都由 MeshWorker::IntegrationInfo<dim>. 提供。请注意，函数的签名不能改变，因为它是由 MeshWorker::integration_loop(). 所期望的。\n\n// 第一个定义局部积分器的类负责计算单元和面矩阵。它被用来组装全局矩阵以及水平矩阵。\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// 在每个单元上，我们对Dirichlet形式进行积分。我们使用LocalIntegrators中的现成积分库来避免自己编写这些循环。同样地，我们实现了Nitsche边界条件和单元间的内部惩罚通量。\n\n// 边界和通量项需要一个惩罚参数，这个参数应该根据单元的大小和多项式的度数来调整。在 LocalIntegrators::Laplace::compute_penalty() 中可以找到关于这个参数的安全选择，我们在下面使用这个参数。\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// 内部面使用内部惩罚方法\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// 第二个局部积分器建立了右手边。在我们的例子中，右手边的函数为零，这样，这里只设置了弱形式的边界条件。\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//第三个局部积分器负责对误差估计的贡献。这是由Karakashian和Pascal（2003）提出的标准能量估计器。\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// 单元的贡献是离散解的拉普拉斯，因为右手边是零。\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// 在边界，我们简单地使用边界残差的加权形式，即有限元解和正确边界条件之间的差值的规范。\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// 最后，在内部面，估计器由解的跳跃和它的法向导数组成，并进行适当的加权。\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// 最后我们有一个误差的积分器。由于不连续Galerkin问题的能量准则不仅涉及到单元内部的梯度差，还涉及到跨面和边界的跳跃项，所以我们不能仅仅使用  VectorTools::integrate_difference().  而是使用MeshWorker接口来自己计算误差。\n\n//有几种不同的方法来定义这个能量准则，但是所有的方法都是随着网格大小的变化而等价的（有些不是随着多项式程度的变化而等价）。这里，我们选择\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// 这里我们有关于单元格的集成。目前MeshWorker中还没有很好的接口可以让我们访问正交点中的正则函数值。因此，我们必须在单元格积分器中创建精确函数值和梯度的向量。之后，一切照旧，我们只需将差值的平方加起来。\n\n// 除了计算能量准则的误差，我们还利用网格工作者的能力同时计算两个函数并在同一个循环中计算<i>L<sup>2</sup></i>的误差。很明显，这个函数没有任何跳跃项，只出现在单元格的积分中。\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// 这个类做主要的工作，就像前面的例子一样。关于这里声明的函数的描述，请参考下面的实现。\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// 与离散化有关的成员对象在这里。\n\n    Triangulation<dim>        triangulation; \n    const MappingQ1<dim>      mapping; \n    const FiniteElement<dim> &fe; \n    DoFHandler<dim>           dof_handler; \n\n// 然后，我们有与全局离散系统相关的矩阵和向量。\n\n    SparsityPattern      sparsity; \n    SparseMatrix<double> matrix; \n    Vector<double>       solution; \n    Vector<double>       right_hand_side; \n    BlockVector<double>  estimates; \n\n// 最后，我们有一组与多级预处理程序相关的稀疏模式和稀疏矩阵。 首先，我们有一个水平矩阵和它的稀疏性模式。\n\n    MGLevelObject<SparsityPattern>      mg_sparsity; \n    MGLevelObject<SparseMatrix<double>> mg_matrix; \n\n// 当我们在局部细化的网格上进行局部平滑的多重网格时，需要额外的矩阵；见Kanschat（2004）。这里是这些边缘矩阵的稀疏性模式。我们只需要一个，因为上矩阵的模式是下矩阵的转置。实际上，我们并不太关心这些细节，因为MeshWorker正在填充这些矩阵。\n\n    MGLevelObject<SparsityPattern> mg_sparsity_dg_interface; \n\n// 精细化边缘的通量矩阵，将精细级自由度与粗略级自由度相耦合。\n\n    MGLevelObject<SparseMatrix<double>> mg_matrix_dg_down; \n\n// 精细化边缘的通量矩阵的转置，将粗级自由度耦合到精细级。\n\n    MGLevelObject<SparseMatrix<double>> mg_matrix_dg_up; \n  }; \n\n// 构造函数简单地设置了粗略的网格和DoFHandler。FiniteElement作为一个参数被提供，以实现灵活性。\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// 在这个函数中，我们设置了线性系统的维度和全局矩阵以及水平矩阵的稀疏性模式。\n\n  template <int dim> \n  void InteriorPenaltyProblem<dim>::setup_system() \n  { \n\n// 首先，我们用有限元将自由度分布在网格上并对其进行编号。\n\n    dof_handler.distribute_dofs(fe); \n    dof_handler.distribute_mg_dofs(); \n    unsigned int n_dofs = dof_handler.n_dofs(); \n\n// 然后，我们已经知道代表有限元函数的向量的大小。\n\n    solution.reinit(n_dofs); \n    right_hand_side.reinit(n_dofs); \n\n// 接下来，我们为全局矩阵设置稀疏性模式。由于我们事先不知道行的大小，所以我们首先填充一个临时的DynamicSparsityPattern对象，一旦完成，就将其复制到常规的SparsityPattern中。\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// 全局系统已经设置好了，现在我们来关注一下级别矩阵。我们调整所有矩阵对象的大小，以便每一级都有一个矩阵。\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// 在为水平矩阵调用<tt>clear()</tt>之后更新稀疏模式很重要，因为矩阵通过SmartPointer和Subscriptor机制锁定了稀疏模式。\n\n    mg_sparsity.resize(0, n_levels - 1); \n    mg_sparsity_dg_interface.resize(0, n_levels - 1); \n\n// 现在，所有的对象都准备好了，可以在每一层容纳一个稀疏模式或矩阵。剩下的就是在每一层设置稀疏模式了。\n\n    for (unsigned int level = mg_sparsity.min_level(); \n         level <= mg_sparsity.max_level(); \n         ++level) \n      { \n\n// 这些与上面的全局矩阵的行数大致相同，现在是每个级别的。\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// 另外，我们需要初始化各层之间细化边缘的转移矩阵。它们被存储在两个索引中较细的索引处，因此在0层没有这样的对象。\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// 在这个函数中，我们组装全局系统矩阵，这里的全局是指我们解决的离散系统的矩阵，它覆盖了整个网格。\n\n  template <int dim> \n  void InteriorPenaltyProblem<dim>::assemble_matrix() \n  { \n\n// 首先，我们需要设置提供我们集成值的对象。这个对象包含了所有需要的FEValues和FEFaceValues对象，并且自动维护它们，使它们总是指向当前单元。为此，我们首先需要告诉它，在哪里计算，计算什么。由于我们没有做任何花哨的事情，我们可以依靠他们对正交规则的标准选择。\n\n// 由于他们的默认更新标志是最小的，我们另外添加我们需要的东西，即所有对象（单元格、边界和内部面）上的形状函数的值和梯度。之后，我们准备初始化容器，它将创建所有必要的FEValuesBase对象进行整合。\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// 这就是我们整合本地数据的对象。它由MatrixIntegrator中的局部整合例程填充，然后由汇编器用来将信息分配到全局矩阵中。\n\n    MeshWorker::DoFInfo<dim> dof_info(dof_handler); \n\n// 此外，我们还需要一个将局部矩阵装配到全局矩阵的对象。这些装配器对象拥有目标对象结构的所有知识，在这里是一个稀疏矩阵，可能的约束和网格结构。\n\n    MeshWorker::Assembler::MatrixSimple<SparseMatrix<double>> assembler; \n    assembler.initialize(matrix); \n\n// 现在是我们自己编码的部分，局部积分器。这是唯一与问题有关的部分。\n\n    MatrixIntegrator<dim> integrator; \n\n// 现在，我们把所有的东西都扔到 MeshWorker::loop(), 中，在这里遍历网格的所有活动单元，计算单元和面的矩阵，并把它们集合到全局矩阵中。我们在这里使用变量<tt>dof_handler</tt>，以便使用全局自由度的编号。\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// 现在，我们对水平矩阵做同样的处理。不太令人惊讶的是，这个函数看起来像前一个函数的孪生兄弟。事实上，只有两个小的区别。\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// 很明显，需要用一个填充水平矩阵的汇编器来代替。请注意，它也会自动填充边缘矩阵。\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// 这里是与前一个函数的另一个不同之处：我们在所有单元上运行，而不仅仅是活动单元。而且我们使用以 <code>_mg</code> 结尾的函数，因为我们需要每一层的自由度，而不是全局的编号。\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// 这里我们有另一个assemble函数的克隆。与组装系统矩阵的区别在于，我们在这里组装了一个向量。\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// 因为这个汇编器允许我们填充多个向量，所以接口要比上面复杂一些。向量的指针必须存储在一个AnyData对象中。虽然这在这里似乎造成了两行额外的代码，但实际上在更复杂的应用中它是很方便的。\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// 现在，我们已经对构建离散线性系统的所有函数进行了编码，现在是我们实际解决它的时候了。\n\n  template <int dim> \n  void InteriorPenaltyProblem<dim>::solve() \n  { \n\n// 选择的求解器是共轭梯度。\n\n    SolverControl            control(1000, 1.e-12); \n    SolverCG<Vector<double>> solver(control); \n\n// 现在我们正在设置多级预处理程序的组件。首先，我们需要在网格层之间进行转移。我们在这里使用的对象为这些转移生成了稀疏矩阵。\n\n    MGTransferPrebuilt<Vector<double>> mg_transfer; \n    mg_transfer.build(dof_handler); \n\n// 然后，我们需要一个精确的解算器来解算最粗层次上的矩阵。\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// 虽然转移和粗略网格求解器几乎是通用的，但为平滑器提供了更多的灵活性。首先，我们选择Gauss-Seidel作为我们的平滑方法。\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// 在每个级别上做两个平滑步骤。\n\n    mg_smoother.set_steps(2); \n\n// 由于SOR方法不是对称的，但我们在下面使用共轭梯度迭代，这里有一个技巧，使多级预处理器成为对称算子，即使是对非对称平滑器。\n\n    mg_smoother.set_symmetric(true); \n\n// 平滑器类可以选择实现变量V型循环，我们在这里不需要。\n\n    mg_smoother.set_variable(false); \n\n// 最后，我们必须将我们的矩阵包裹在一个具有所需乘法函数的对象中。\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// 现在，我们准备设置V型循环算子和多级预处理程序。\n\n    Multigrid<Vector<double>> mg( \n      mgmatrix, mg_coarse, mg_transfer, mg_smoother, mg_smoother); \n\n// 让我们不要忘记因为自适应细化而需要的边缘矩阵。\n\n    mg.set_edge_flux_matrices(mgdown, mgup); \n\n// 在所有的准备工作完成后，将Multigrid对象包装成另一个对象，它可以作为一个普通的预处理程序使用。\n\n    PreconditionMG<dim, Vector<double>, MGTransferPrebuilt<Vector<double>>> \n      preconditioner(dof_handler, mg, mg_transfer); \n\n// 并用它来解决这个系统。\n\n    solver.solve(matrix, solution, right_hand_side, preconditioner); \n  } \n\n// 另一个克隆的集合函数。与之前的最大区别是，这里我们也有一个输入向量。\n\n  template <int dim> \n  double InteriorPenaltyProblem<dim>::estimate() \n  { \n\n// 估算器的结果存储在一个每个单元格有一个条目的向量中。由于deal.II中的单元格没有编号，我们必须建立自己的编号，以便使用这个向量。对于下面使用的汇编器来说，结果存储在向量的哪个分量中的信息是由每个单元的user_index变量传送的。我们需要在这里设置这个编号。\n\n// 另一方面，有人可能已经使用了用户指数。所以，让我们做个好公民，在篡改它们之前保存它们。\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// 这就像以前一样开始。\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对象，这个向量就是我们刚刚计算的解。\n\n    AnyData solution_data; \n    solution_data.add<const Vector<double> *>(&solution, \"solution\"); \n\n// 然后，我们告诉单元格的 Meshworker::VectorSelector ，我们需要这个解决方案的二次导数（用来计算拉普拉斯）。因此，选择函数值和第一导数的布尔参数是假的，只有选择第二导数的最后一个参数是真的。\n\n    info_box.cell_selector.add(\"solution\", false, false, true); \n\n// 在内部和边界面，我们需要函数值和第一导数，但不需要第二导数。\n\n    info_box.boundary_selector.add(\"solution\", true, true, false); \n    info_box.face_selector.add(\"solution\", true, true, false); \n\n// 我们继续像以前一样，除了默认的更新标志已经被调整为我们上面要求的值和导数之外。\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// 汇编器在每个单元格中存储一个数字，否则这与右侧的计算是一样的。\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// 就在我们返回错误估计的结果之前，我们恢复旧的用户索引。\n\n    triangulation.load_user_indices(old_user_indices); \n    return estimates.block(0).l2_norm(); \n  } \n\n// 这里我们把我们的有限元解和（已知的）精确解进行比较，计算梯度和函数本身的平均二次误差。这个函数是上面那个估计函数的克隆。\n\n// 由于我们分别计算能量和<i>L<sup>2</sup></i>-norm的误差，我们的块向量在这里需要两个块。\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// 创建图形输出。我们通过整理其各个组成部分的名称来产生文件名，包括我们用两个数字输出的细化周期。\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// 最后是自适应循环，或多或少和前面的例子一样。\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": "#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": "//  (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": "//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": "//\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 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": "//\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ées par une interpolation par spline cardinale.\n *\n * Les rotations sont obtenus de la manière suivante :\n *\n * Chaque keyframe se voit associé 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ée 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égatif.\n *\n * La tangente T en un keyframe est donnée par le vecteur reliant ses voisins (AC pour le point B),\n * c'est le même 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ésentant la rotation à ce keyframe.\n *\n * On obtient les rotations intermédiaires 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éaire 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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#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": "#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": "//  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": "#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        // 选择迭代策略，通常还是L-M算法居多\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": "#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}; /* 実行するアルゴリズム */\nstatic const std::vector<string> algo_name{\"Lloyd\", \"Hamerly\", \"Elkan\"};\n\n#define BENCH 1\n/* k-meansの各種のアルゴリズムのベンチマークを取るときに1*/\n\n#if BENCH\nint bench_show\n(ostream &stream,            /* 出力先 */\n enum algorithm method,      /* 使用したアルゴリズム */\n const unsigned int n,       /* データ点数 */\n const unsigned int d,       /* 次元数 */\n const unsigned int k,       /* クラスタ数 */\n const struct timeval start, /* 開始時刻 */\n const struct timeval end,   /* 終了時刻 */\n const unsigned int rep,     /* 繰り返し回数 */\n const ublas::matrix<double> x,       /* データ点 */ \n const ublas::vector<unsigned int> a, /* 割り当てクラスタ */\n const ublas::matrix<double> c)       /* クラスタ中心 */\n{  \n  double err_sum = 0; /* 二乗誤差和を計算する */\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\" /* 実行時間(us) */\n\t << (err_sum / n)  << \"\\t\" << rep << endl;\n  return 0;\n}\n#endif\n\n\n/* 全てのアルゴリズムに共通 */\nint initialize_centers\n(const unsigned int k,\n const ublas::matrix<double> x,\n ublas ::matrix<double> &c)\n{\n  /* とりあえず適当に最初のデータ点を充てる */\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){ /* 実行時オプションが少ないときのエラー処理 */\n    /* 使い方を表示して異常終了 */\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    /* 実行時オプションの処理 */    \n    enum algorithm method; /* 実行するアルゴリズム */\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{ /* 指定されたアルゴリズムが不明 */\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 のときのエラー処理 */\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個のd次元データをファイルから読み込む */\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    /* クラスタリングの結果を書き込むメモリ領域の確保 */\n    ublas::vector<unsigned int> a(n, 0); /* 各点x_iが属するクラスタ */\n    ublas::matrix<double> c(k,d,0);      /* クラスタの重心 */\n    unsigned int rep = 0;                /* 繰り返し回数 */ \n\n    /* 初期クラスタ中心を何らかの方法で得る */\n    initialize_centers(k, data, c);\n\n    \n#if BENCH /* プログラム実行時間のベンチマークを取る */\n    struct timeval t_start, t_end;\n    gettimeofday(&t_start, NULL); /* 時間計測開始 */\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); /* 時間計測終了 */\n#endif\n\n    { /* 結果を出力 */\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": "#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": "/**\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": "#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": "#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 − 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} − 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": "/* -*- 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": "/* 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": "/**\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": "/** \\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 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": "// 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": "/*\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änkt), 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": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// 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": "#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// β-detected nuclear magnetic resonance (β-NMR)\nnamespace bnmr {\n\n// β-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": "// 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": "#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": "/***************************************************************************\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": "/* 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": "/* -*- 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 <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 <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": "//==================================================================================================\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": "//==============================================================================\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": "#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 \"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": "#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": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n#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ähler 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": "/* 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": "/* =========================================================================\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": "/*\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": "\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": "#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": "#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": "// 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": "#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": "/** \\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": "//---------------------------------------------------------------------------//\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": "/*\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åkon 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 *      @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 * 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": "/*\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 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": "//  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": "#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 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// 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": "#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": "#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": "// ---------------------------------------------------------------------\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": "// 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 Pa / K mol]\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 <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": "#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": "/**\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": "//  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": "#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": "// 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à.\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 è 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à. 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 è 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 è 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 è uguale a `1`.\n            static_if(bool_v<(order() == 1)>)\n                .then([&result](const auto& x)\n                    {\n                        // Se l'ordine è 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ù 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 è triangolare superiore.\n            for(int i(n - 1); i >= 0; i--)\n            {\n                // Setta `i`-esimo risultato.\n                // `a(i, n)` è inizialmente un termine noto.\n                // `a(i, i)` è 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ù 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ù 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": "/**\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": "//  (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": "//==============================================================================\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 \"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": "// 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": "/*\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": "#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": "﻿#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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#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": "//****************************************************************************\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": "#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": "// 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": "#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": "//==============================================================================\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": "#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": "#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": "\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": "#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 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés\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": "// 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, “A tutorial on se (3) transformation parameterizations\n *           and on-manifold optimization,” Univ. Malaga, Tech. Rep, no. 3,\n *           pp. 1–56, 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": "#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": "#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 *  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 \"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": "///////////////////////////////////////////////////////////////////////////////\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 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": "#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": "/**\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 * 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    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 |ä| 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äumlicher \n  // geodätischer Koordinaten aud rechtwinkeligen Koordinaten\", Zeitschrift für \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 ) << \"°\" << convertToString(northSouth) << \", \"\n         << AMG::Units::radian2degree( lon_rad ) << \"°\" << 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": "#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": "/* 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": "/*\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": "/* 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": "// 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": "#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 * 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 *    “Motion Planning for Autonomous Driving with a Conformal Spatiotemporal\n * Lattice.” In 2011 IEEE International Conference on Robotics and Automation,\n * 4889–95.\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": "/* ----------------------------------------------------------------------------\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": "// 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": "// 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": "//  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": "/*****************************************************************************\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\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": "//   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": "\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": "//\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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#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": "// 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": "#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; //摄像头的分辨率\nconst int imageHeight = 480;\nconst int boardWidth = 9;                         //横向的角点数目\nconst int boardHeight = 6;                        //纵向的角点数据\nconst int boardCorner = boardWidth * boardHeight; //总的角点数据\nconst int squareSize = 25;                        //标定板黑白格子的大小 单位mm\nconst Size imageSize = Size(imageWidth, imageHeight);\n\nconst Size boardSize = Size(boardWidth, boardHeight);\nMat intrinsicL;                   //相机内参数\nMat distortion_coeffL;            //相机畸变参数\nvector<Mat> rvecsL;               //旋转向量\nvector<Mat> tvecsL;               //平移向量\nvector<vector<Point2f>> cornersL; //各个图像找到的角点的集合 和objRealPoint 一一对应\n\nMat intrinsicR;                   //相机内参数\nMat distortion_coeffR;            //相机畸变参数\nvector<Mat> rvecsR;               //旋转向量\nvector<Mat> tvecsR;               //平移向量\nvector<vector<Point2f>> cornersR; //各个图像找到的角点的集合 和objRealPoint 一一对应\nvector<Mat> intrinsics, distortion_coeffs;\n\nvector<vector<Point3f>> objRealPoint; //各副图像的角点的实际物理坐标集合\n\nvector<Point2f> cornerL; //某一副图像找到的角点\nvector<Point2f> cornerR; //某一副图像找到的角点\n\nMat R, T, E, F;                 //R 旋转矢量 T平移矢量 E本征矩阵 F基础矩阵\nMat Rl, Rr, Pl, Pr, Q;          //校正旋转矩阵R，投影矩阵P 重投影矩阵Q (下面有具体的含义解释）\nMat mapLx, mapLy, mapRx, mapRy; //映射表\nRect validROIL, validROIR;      //图像校正之后，会对图像进行裁剪，这里的validROI就是指裁剪之后的区域\n\n//相机内参矩阵\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; //各个图像找到的角点的集合 和objRealPoint 一一对应\nvector<float> vrms;\n\nCalibration::Calibration()\n{\n}\n\n/*计算标定板上模块的实际物理坐标*/\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    //指定亚像素计算迭代标注\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        /*计算实际的校正点的三维坐标*/\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; //旋转向量\n        vector<Mat> tvecs; //平移向量\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        /*计算实际的校正点的三维坐标*/\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        //标定摄像头\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        //立体校正的时候需要两幅图像共面并且行对准 以使得立体匹配更加的可靠\n        //使得两幅图像共面的方法就是把两个摄像头的图像投影到一个公共成像面上，这样每幅图像从本图像平面投影到公共图像平面都需要一个旋转矩阵R\n        //stereoRectify 这个函数计算的就是从图像平面投影都公共成像平面的旋转矩阵Rl,Rr。 Rl,Rr即为左右相机平面行对准的校正旋转矩阵。\n        //左相机经过Rl旋转，右相机经过Rr旋转之后，两幅图像就已经共面并且行对准了。\n        //其中Pl,Pr为两个相机的投影矩阵，其作用是将3D点的坐标转换到图像的2D点的坐标:P*[X Y Z 1]' =[x y w]\n        //Q矩阵为重投影矩阵，即矩阵Q可以把2维平面(图像平面)上的点投影到3维空间的点:Q*[x y d 1] = [X Y Z W]。其中d为左右两幅图像的时差\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": "#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": "/******************************************************************************\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 * @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": "﻿\n\n/*\n********************************************************************\n版本声明：\n\t\t\t\t\t\t\t\t   ╭════════════════════════╮\n\t\t\t\t\t\t\t\t  ║         〖课题设计：〗         ║\n\t\t ╭══════════════════════┤设计时间：2020.4.17 ├══════════════════╮\n\t\t║                        ║   设计人：  2016级工业工程专业 邝伟杜Tridu³³     ║                            ║\n\t\t║                        ╰═════════════════════════╯                            ║\n\t  　║                                        ★    关于    Code     ★                                         ║\n\t\t║   @计算机配置：windows 10 教育版 64位操作系统 内存：4G CPU ：i3--6100\t\t                            ║\n\t\t║   @运行环境：Microsoft Visual C++ 2010\t\t\t\t                                                    ║\n\t\t║   @设计思路：建立多个子函数，分别用作缓冲区无限的串行生产线建模.\t\t\t\t                            ║\n  　  　║--------------------------------------------------------------------------------------------------------- ║\n\t  　║                                        ★      @主要函数       ★                                        ║\n  　    ║                              |----------------------------------------------|                            ║\n\t\t║\t\t\t\t1 极大代数法的乘法MP_RealNumberTimes、2 极大代数系统的矩阵乘法MP_MaTimesMb、\t\t\t\t║\n\t\t║\t\t\t    3 极大代数法的加法MP_RealNumberPlus、4 矩阵A的极大代数法k次幂MP_AKpower、\t\t\t    \t║\n\t\t║\t\t\t\t5 极大代数矩阵的星运算MP_Mastar、6 判断矩阵的可简约性并给出不可简约矩阵的特征值MP_MaValue、 ║\n\t\t║\t\t\t\t7 计算串行生产线开环系统的参数矩阵ABC:T2ABCmatrix、\t                            \t\t\t║\n\t\t║\t\t\t\t8 给出反馈矩阵K计算闭环线性模型M,N矩阵MP_KT2MN\t\t\t                                \t║\n\t\t║\t\t\t    主函数控制管理了各个函数结构，其实需要外部使用，\t\t\t                            \t║\n\t\t║\t\t\t    只需要把功能函数extern，写成dll提供给其他函数调用就行在主函数t_main(GUI应用本质就是通过各种 ║\n\t\t║  组件调用函数传递参数，其实逻辑类似，这里目标是说明功能GUI应用懒得整了)中，可以以1、2、3、4、5、6、7、8、║\n\t\t║  9、10数字键分别可以执行某个功能模块。                                                                   ║\n\t\t║\t\t\t\t限教学使用交流！请勿用于商业目的。                                                          ║\n　      ║----------------------------------------------------------------------------------------------------------║\n\t\t║                          欢迎提出您的建议或意见，请发邮件:2055969978@qq.com                              ║\n\t\t║----------------------------------------------------------------------------------------------------------║\n\t　　║                                                                                                          ║\n\t\t║                     ╭──────────────────────────────╮                     ║\n\t\t╰══════════┤   ★★★★★★  Tridu³³，tridu33@qq.com★★★★★★★     ├══════════╯\n\t\t\t\t\t\t\t  ╰───────────────────────────────╯\n\n\n******************************************************************\n*/\n\n// MaxPlus_ABC.cpp : 定义控制台应用程序的入口点。\n//\n#define _CRT_SECURE_NO_WARNINGS ; \n// 包括 SDKDDKVer.h 将定义可用的最高版本的 Windows 平台。\n\n// 如果要为以前的 Windows 平台生成应用程序，请包括 WinSDKVer.h，并将\n// WIN32_WINNT 宏设置为要支持的平台，然后再包括 SDKDDKVer.h。\n//在此处引用程序需要的其他头文件\n//编译程序会先从当前目录中找文件，生成预编译头文件！预编译，是为了提高编译速度！\n#include <SDKDDKVer.h>\n#include <stdio.h>\n#include <tchar.h>//一般是用双引号来引用自己编写的文件，而用尖括号引用系统标准的文件。\n#include<stdlib.h>//用于数值转换、内存分配以及具有其他相似任务的函数。free()\n#include<conio.h>//Console Input/Output（控制台输入输出）的简写，其中定义了通过控制台进行数据输入和数据输出的函数，主要是一些用户通过按键盘产生的对应操作，比如getch()函数等等。\n#include<string.h>//字符串处理\n#include<dos.h>//包含了很多BIOS和DOS调用函数\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>//整型无穷大小，INT_MAX表示正无穷，-DBL_MAX表示负无穷\n#include <float.h>//double 型的无穷大小，用DBL_MAX表示正无穷，-DBL_MAX表示负无穷(注意不是DBL_MIN)\n\n\nusing namespace Eigen;\nusing namespace std;\n\n\n//声明函数\t\n/*\n1 极大代数法的乘法MP_RealNumberTimes();\n2 极大代数系统的矩阵乘法MP_MaTimesMb();\n3 极大代数法的加法MP_RealNumberPlus();\n4 矩阵A的极大代数法k次幂MP_AKpower();\n5 极大代数矩阵的星运算MP_Mastar();\n6 判断矩阵的可简约性并给出不可简约矩阵的特征值MP_MaValue();\n7 计算串行生产线开环系统的参数矩阵ABC:T2ABCmatrix();\n8 给出反馈矩阵K计算闭环线性模型M,N矩阵MP_KT2MN();\n\n*/\n\n\n//-------------------------------------------------------------------------\n//Octave编程语言省略了繁琐的变量声明和函数调用，在把Octave代码编程实现为C++的过程中，需要增加代码中的Octave库的结构体和函数，Octave代码不能生成exe或者dll,老师建议我用c++造一遍轮子，我觉得也许c++大型数据结构精度计算优化可能会好一些吧。\n//根据code，需要定义的结构体和函数(轮子)：\n//col collist(k)列向量结构体=一维数组=特殊的二维矩阵\n//row rowlist(k)行向量结构体=一维数组=特殊的二维矩阵\n//matrix矩阵结构体=二维数据\n//泛型函数max\n//int result = max(collist)取行向量大值\n//max(rowlist)取列向量大值\n//max(matrix)取二维数组matrix最大值\n//collist diag(matrix H)\n//返回值[int m,int n]=函数名size(arg*参数matrix matrix_mn)取大小\n//[matrix matrix_ones]=ones(int m,int n);\n//......太麻烦了，所以：\n//人生苦短，我选Eigen!\nMatrixXd readMatrixFromTXT(string dir);\nint colT = 0;//T每列数初始0\nint rowT = 0;//T每行数量初始值0,变量作用域\nMatrixXd readMatrixFromTXT(string dir) {\n\tstring line;\n\tifstream in(dir);  //读入文件\n\tregex pat_regex(\"[[:digit:]]+\");  //匹配原则，这里代表一个或多个数字\n\t//获取矩阵rowT,colT\n\twhile (getline(in, line)) {  //按行读取\n\t\trowT++;\n\t\tcolT = 0;//每行列数设置初始0,变量作用域\n\t\tfor (sregex_iterator it(line.begin(), line.end(), pat_regex), end_it; it != end_it; ++it) {  //表达式匹配，匹配一行中所有满足条件的字符\n\t\t\tcolT++;//colT++\n\t\t}\n\t};\n\tMatrixXd T = MatrixXd::Ones(rowT, colT);//注意行列数从0开始\n\t//赋值\n\tint i = 0;//每列 index初始0\n\tint j = 0;//每行 index初始值0\n\tifstream in2(dir);\n\twhile (getline(in2, line)) {  //按行读取\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) {  //表达式匹配，匹配一行中所有满足条件的字符\n\t\t\t//cout << it->str() << \" \";  //输出匹配成功的数据\n\t\t\tj++;\n\t\t\tT(i - 1, j - 1) = stoi(it->str());  //将数据转化为int型并存入\n\t\t}\n\t};\n\tin.close(); in2.close();\n\treturn T;\n}\n\n\n\n/*非常不好用的Octave混合编程\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//菜单MatrixXd\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\");    //清屏\n\tsystem(\"mode con cols=150 lines=45\");\n\tsystem(\"color f0\");//改变控制台前景，背景颜色\n\tsystem(\"title 基于极大代数法的串行生产线计算工具包\");\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\");//显示系统当前日期\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\");//显示系统当前时间，\\t是没有反应的\n\tprintf(\"\\n\\n\\n\\n\\n\");\n\tprintf(\"\\t\\t\\t\\t ╭════════════════════════════════════════════════╮\\n\");\n\tprintf(\"\\t\\t\\t\\t            〖课题设计：MaxPlus_ABC〗          \\n\");\n\tprintf(\"\\t ╭══════════════════════════════════┤  设计时间：2020.4.20 ├════════════════════════════════════════════════╮\\n\");\n\tprintf(\"\\t\\t\\t\\t               设计人：Tridu33                                                                              \\n\");\n\tprintf(\"\\t\\t\\t\\t╰ ════════════════════════════════════════════════╯                             \\n\");\n\tprintf(\"\\t║---------------------------------------------------------------------------------------------------------- ║\\n\");\n\tprintf(\"\\t║                                        ★    Menu菜单     ★                                              ║\\n\");\n\tprintf(\"\\t║---------------------------------------------------------------------------------------------------------- ║\\n\");\n\tprintf(\"\\t║                                    1.极大代数法的乘法MP_RealNumberTimes();                                ║\\n\");\n\tprintf(\"\\t║                                    2.极大代数系统的矩阵乘法MP_MaTimesMb();                                ║\\n\");\n\tprintf(\"\\t║                                    3.极大代数法的加法MP_RealNumberPlus();                                 ║\\n\");\n\tprintf(\"\\t║                                    4.矩阵A的极大代数法k次幂MP_AKpower();                                  ║\\n\");\n\tprintf(\"\\t║                                    5.极大代数矩阵的星运算MP_Mastar();                                     ║\\n\");\n\tprintf(\"\\t║                                    6.判断矩阵的可简约性并给出不可简约矩阵的特征值MP_MaValue();            ║\\n\");\n\tprintf(\"\\t║                                    7.计算串行生产线开环系统的参数矩阵ABC:T2ABCmatrix();                   ║\\n\");\n\tprintf(\"\\t║                                    8.给出反馈矩阵K计算闭环线性模型M,N矩阵MP_KT2MN();                      ║\\n\");\n\tprintf(\"\\t║                                    9.exit退出                                                             ║\\n\");\n\tprintf(\"\\t║                                    10.关于                                                                ║\\n\");\n\tprintf(\"\\t║\\t     ╭───────────────────────────────────────────────────────────────────────────────╮              ║\\n\");\n\tprintf(\"\\t║═══════════┤ ★★★★★★  欢迎提出您的建议或意见，请发邮件:tridu33@qq.com    ★★★★★★★├══════════════║\\n\");\n\tprintf(\"\\t║\\t     ╰───────────────────────────────────────────────────────────────────────────────╯\\n\\n\\n\\n\");\n\n\tprintf(\"\\t\\t\\t请您选择(1-10):\\t\");\n}\n\n\n//-------------------------------------------------------------------------MatrixXd\n//1 极大代数法的乘法MP_RealNumberTimes();\n\nint MP_RealNumberTimes(int a, int b) {\n\tprintf(\"\\n极大代数法的乘法MP_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 极大代数系统的矩阵乘法MP_MaTimesMb();\nMatrixXd MP_MaTimesMb(MatrixXd Ma, MatrixXd Mb) {\n\t//printf(\"极大代数系统的矩阵乘法MP_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会溢出导致结果0，而不会出现保持-DBL_MAX的结果，所以需要自定义，-DBL_MAX遇到什么数字相加都==-DBL_MAX\n\t\t\t\t\telse //其中有一个加数是-DBL_MAX,结果不用算数计算,溢出，而应该直接令结果为-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%%矩阵A(m*r)极大代数乘矩阵B(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 极大代数法的加法MP_RealNumberPlus();\nint MP_RealNumberPlus(int a,int b) {\n\t//printf(\"\\n极大代数法的加法MP_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矩阵加法其实就是取大操作，后续懒得写出来，直接写了在需要调用的地方\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 矩阵A的极大代数法k次幂MP_AKpower();\n\tMatrixXd  MP_AKpower(MatrixXd A, int k) {\n\t\t//printf(\"\\n矩阵A的极大代数法k次幂MP_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初始值E矩阵\n\t\t//cout << \"初始值AK=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%矩阵A的极大代数法k次幂\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 极大代数矩阵的星运算MP_Mastar();\n\n\nMatrixXd MP_Mastar(MatrixXd A) {\n\t//printf(\"\\n极大代数矩阵的星运算MP_Mastar\\n \");\n\tint m = A.rows(); int n = A.cols();\n\tMatrixXd AK = MatrixXd::Ones(m, m);//初始化矩阵大小,最后不取all 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不是下标，不许-1\n\t\t//cout<<\"k=\"<<k<<endl;\n\t\tAK = MP_AKpower(A, k);// A的k次幂，k = 0; < dim(A) - 1,Astr是累计的矩阵结果,AK是每次极大代数加法新进去的矩阵\n\t//\tcout <<\"AK=\"<<AK<< endl;//MaPlusMb矩阵的极大代数加法Astronauts，Astr\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%%极大代数的方阵星运算实现\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的k次幂，k=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 判断矩阵的可简约性并给出不可简约矩阵的特征值MP_MaValue();\n\n\ndouble MP_MaValue(MatrixXd A) {\n\tprintf(\"\\n判断矩阵的可简约性并给出不可简约矩阵的特征值MP_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++) {//不是下标不许-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++循环变量-1就不需要下标变动，但是比较麻烦的下标推理的情况下：还是用的下标-1，循环条件不变比较好。\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%判断矩阵的可简约性，并给出不可简约矩阵的特征值\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 计算串行生产线开环系统的参数矩阵ABC: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//构造矩阵A:\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);//最快的方法是只改下标-1，循环条件不变，改前A(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);//最快的方法是只改下标-1，循环条件不变，改前A(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); //构造矩阵B:\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);//构造矩阵C:\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%% 串行生产线开环系统的参数矩阵实现\nfunction [A,B,C]=T2ABCmatrix(T)\n  [m,n]=size(T);%%构造矩阵A:\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对角元素下方元素下标k*n+i+1,j*n+i\n\t\t\tfor i=1:n-1%%对角分块t_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 %%对焦分块的左下分块t_x1-t_xn\n\t\t\tA(k*n+i,j*n+i)=T(k,i);\n\t\t\tendfor\n\t  %endif%如果第11行写成else if理解为两个if else语句\n\t  endif%if\n\tendfor\n  endfor\n\n  B=-inf*ones(m*n,m+n); %%构造矩阵B:\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);%%构造矩阵C:\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 给出反馈矩阵K计算闭环线性模型M,N矩阵MP_KT2MN();\n\n\n\nvoid MP_KT2MN(MatrixXd K, MatrixXd T){\n\tprintf(\"\\n给出反馈矩阵K计算闭环线性模型M,N矩阵MP_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%%极大代数，给出反馈矩阵K计算M,N矩阵\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 输入0返回主菜单\");\n\tchar c;\n\t//文件输入\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 卡了三天的问题原来在这儿！！！！让流回到控制台?使用freopen后如何将stdout输出流还原回屏幕？\n\t//break;//步进没问题，但是不知道为什么不能只执行一次，死循环\n\tprintf(\"\\n\\n\");\n\tsystem(\"pause\");\n\t//exit(1);\n}\n\n//-------------------------------------------------------------------------\n\n/*本人精通面向佛系的编程语言，有空交流\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   佛祖保佑         永无BUG\n*/\n///////////////////////////////////////////////////////////////////////////////////////////////\nvoid welcomevoice();\nvoid welcomevoice() {\n\tchar uerInputData[2][100] = { \"欢迎使用\" };\n\tint welcome = 0;\n\twhile (1) {\n\t\tFILE* pFile = fopen(\"voice.vbs\", \"w\");//msgbox\"自\"//CreateObject(\"SAPI.SpVoice\").Speak\"能\"//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)函数外只能定义全局变量或者对象，而不能执行语句及调用函数。//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矩阵有\" << rowT << \"行\" << colT << \"列\" << 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矩阵有\" << Kread.rows() << \"行\" << Kread.cols() << \"列\" << endl;\n//-------------------------------读取矩阵T,获得变量rowT,colT,矩阵K,获得变量rowK,colK---------------------------------------//\n\tint c;\n\tchar ch[7];\n\tint i, n;\n\tsystem(\"color 0f\");//改变控制台前景，背景颜色\n\tsystem(\"title MaxPlus_ABC\");\n\twelcomevoice();//欢迎使用\n\tprintf(\"\\t\\t\\t password(111):\");\n\t//---------\n\t\n\tfor (i = 0; i < 3; i++) {\n\t\t//获取ch\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//匹配ch和password\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 << \"矩阵：\\n\"<< testA <<endl;\n\t\t\t\t\tcout << \"矩阵自身矩阵相乘k=0次：\\n\" << tmpE << endl;\n\t\t\t\t\tcout << \"矩阵自身矩阵相乘k=1次：\\n\" << MP_AKpower(testA, 1) << endl;\n\t\t\t\t\tcout << \"矩阵自身矩阵相乘k=2次：\\n\" << MP_AKpower(testA, 2) << endl;\n\t\t\t\t\tcout << \"矩阵自身矩阵相乘k=3次：\\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的A矩阵：\\n\" << tmp << endl; \n\t\t\t\t\tcout << \"矩阵星运算：\\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 << \"矩阵：\\n\" << tmp << endl; \n\t\t\t\t\tcout << \"A矩阵特征值(8默认值)：\" << 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(\"该编号的新功能有待开发中...\"); break;\n\t\t\t\tcase 9: return 0;\n\t\t\t\t};\n\t\t\t\t_getch();//会等待你按下任意键，再继续执行下面的语句\n\t\t\t\tmenu();\n\t\t\t\tscanf(\"%d\", &c);//可以换成sscanf_(\"%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(\"密码错误,请重新输入\\n\");\n\t\t}\n\n\t}\n\tif (i == 3) {\n\t\tprintf(\"你输入的错误的密码次数达到上限，系统自动退出！请联系管理员！\");\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": "#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": "//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;  //для работы с бесконечными дробями в полиномиальной функции\n\n/* Split строки по пробелам */\nstd::vector<std::string> split(std::string line) {\n    std::vector<std::string> words;\n    std::string buffer = \"\";      //буфферная строка\n    for(int i=0; i <= line.size(); i++){\n        if(line[i] != ' '){      // \" \" сплиттер\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/* Возвращает 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/* Генерация приватного ключа ECDSA сurve25519 */\nstd::string curve25519_pr_key_gen() {\n    unsigned char buf[32];\n    RAND_bytes(buf, 32);  //генерируем 32 рандомных байта\n    std::string s_buf;\n    s_buf += std::string(buf, buf+32);  //переводим unsigned char buf в std::string\n    std::string curve25519_pr_key = sha256(s_buf);\n    return curve25519_pr_key;\n}\n\n/* Возвращает результат полинома n-1 степени от 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;  //текущая степень x\n\n    BIGNUM *sum = NULL;  //результат полинома без сложения с секретом\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);  //переводим коэффициент в BIGNUM(hex)\n\n        BIGNUM *pow = NULL;  //результат возведения в степень 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++) {  //возводим x в степень j\n            BN_mul(pow, our_x, pow, ctx);\n        }\n\n        BN_mul(coef_res, pow, coef_res, ctx);  //результат x*a(j)\n        BN_add(sum, sum, coef_res);  //накапливаем сумму a(j)*x^j\n\n        j++;\n        BN_free(coef_pov_res);\n        BN_free(coef_res);\n    }\n\n    BIGNUM *p = NULL;  //переводим secret в BIGNUM\n    const char *pr_key = secr.c_str();\n    BN_hex2bn(&p, pr_key);\n    BN_add(result, p, sum);  //результат полинома\n\n    return result;\n}\n\n/* Разделение секрета на N частей */\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;  //куски - точки типа (int; BIGNUM)\n\n    std::vector<std::string> coefs;  //массив рандомных коэффициентов полинома\n\n    for (int i=1; i<t; i++) {  //генерация t-1 коэффициентов\n        unsigned char buf[16];\n        RAND_bytes(buf, 16);  //генерируем 32 рандомных байта коэффициента\n        std::string str_buf((char*)buf);\n        std::string cur_cof = sha256(str_buf);  //коэффициент - sha256(random 32 bytes)\n        coefs.push_back(cur_cof);\n    }\n\n    for (int i=0; i<n; i++) {  //запись n кусков в массив пар 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});  //записываем точку (i+1; share[i+1])\n\n        BN_free(share);\n        OPENSSL_free(number_str);\n    }\n\n    return shares_bignum;\n}\n\n/* Восстановление секрета по T частям */\nstd::string recover(std::vector<std::pair<int, std::string>> shares) {\n    std::vector<double> x;  //коэффициенты x частей секрета\n    std::vector<std::string> y;  //коэффициенты y частей секрета\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    /* Возвращение исходной полиномиальной функции */\n    std::vector<mp_type> x_divs;\n    for (int j=0; j<x.size(); j++) {  //считаем частные\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) {  //умножаем каждый x на соответствующий 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;  //складываем результаты умножений\n\n        ind_cur_y++;\n    }\n    cpp_int res_int(result+1);  //из-за округления double приходится прибавлять единицу\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 << \"Проверьте правильность введенных вами данных!\\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();  //генерация приватного ключа\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);  //разделение приватного ключа на N кусков\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 != \"\") {  //ввод частей в режиме recover с клавиатуры\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": "// 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// 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ément 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": "#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": "\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// 关于包含文件的解释，读者应该参考示例程序  step-1  到  step-4  。它们的标准顺序是  <code>base</code> -- <code>lac</code> -- <code>grid</code>  --  <code>dofs</code> -- <code>fe</code> -- <code>numerics</code>  （因为每一类大致都是建立在前面的基础上），然后是一些用于文件输入/输出和字符串流的C++头文件。\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// 最后一步和以前所有的程序一样。\n\nnamespace Step25 \n{ \n  using namespace dealii; \n// @sect3{The <code>SineGordonProblem</code> class template}  \n\n// 解决问题的整个算法被封装在这个类中。和以前的例子程序一样，这个类在声明时有一个模板参数，就是空间维度，这样我们就可以在一个、两个或三个空间维度上解决正弦-戈登方程。关于这个问题的独立于维度的类封装的更多信息，读者应该参考  step-3  和  step-4  。\n\n// 与 step-23 和 step-24 相比，在程序的总体结构中没有任何值得注意的地方（当然，在各种函数的内部运作中也有！）。最明显的区别是出现了两个新的函数 <code>compute_nl_term</code> 和 <code>compute_nl_matrix</code> ，计算系统矩阵的非线性贡献和第一个方程的右手边，正如在介绍中讨论的那样。此外，我们还必须有一个向量 <code>solution_update</code> ，它包含在每个牛顿步骤中对解向量的非线性更新。\n\n// 正如介绍中也提到的，我们在这个程序中不存储速度变量，而是质量矩阵乘以速度。这是在 <code>M_x_velocity</code> 变量中完成的（\"x \"是代表 \"次数\"）。\n\n// 最后， <code>output_timestep_skip</code> 变量存储了在生成图形输出前每次所需的时间步数。这一点在使用精细网格（因此时间步数较小）时非常重要，在这种情况下，我们会运行大量的时间步数，并创建大量的输出文件，这些文件中的解决方案在后续文件中看起来几乎是一样的。这只会堵塞我们的可视化程序，我们应该避免创建比我们真正感兴趣的更多的输出。因此，如果这个变量被设置为大于1的值 $n$ ，那么只有在每一个 $n$ 的时间步长时才会产生输出。\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// 在下面两类中，我们首先实现了本程序介绍中提到的一维、二维和三维的精确解。如果想通过比较数值解和分析解来测试程序的准确性，那么这个时空解可能会有独立的意义（但是请注意，程序使用的是有限域，而这些是无界域的分析解）。例如，这可以用 VectorTools::integrate_difference 函数来完成。再次注意（正如在 step-23 中已经讨论过的），我们如何将时空函数描述为依赖于时间变量的空间函数，该变量可以使用FunctionTime基类的 FunctionTime::set_time() 和 FunctionTime::get_time() 成员函数进行设置和查询。\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// 在本节的第二部分，我们提供初始条件。我们很懒惰（也很谨慎），不想第二次实现与上面相同的函数。相反，如果我们被查询到初始条件，我们会创建一个对象 <code>ExactSolution</code> ，将其设置为正确的时间，并让它计算当时的精确解的任何值。\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// 让我们继续讨论主类的实现，因为它实现了介绍中概述的算法。\n\n//  @sect4{SineGordonProblem::SineGordonProblem}  \n\n// 这是 <code>SineGordonProblem</code> 类的构造函数。它指定了所需的有限元的多项式程度，关联了一个 <code>DoFHandler</code> to the <code>triangulation</code> 对象（就像在示例程序 step-3 和 step-4 中一样），初始化了当前或初始时间、最终时间、时间步长，以及时间步长方案的 $\\theta$ 值。由于我们在这里计算的解是时间周期性的，所以开始时间的实际值并不重要，我们选择它是为了让我们在一个有趣的时间开始。\n\n// 请注意，如果我们选择显式欧拉时间步进方案（ $\\theta = 0$ ），那么我们必须选择一个时间步进 $k \\le h$ ，否则该方案不稳定，解中可能出现振荡。Crank-Nicolson方案（ $\\theta = \\frac{1}{2}$ ）和隐式Euler方案（ $\\theta=1$ ）不存在这个缺陷，因为它们是无条件稳定的。然而，即使如此，时间步长也应选择在 $h$ 的数量级上，以获得一个好的解决方案。由于我们知道我们的网格是由矩形的均匀细分而来，我们可以很容易地计算出这个时间步长；如果我们有一个不同的域， step-24 中的技术使用 GridTools::minimal_cell_diameter 也是可以的。\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// 这个函数创建了一个 <code>dim</code> 维度的矩形网格，并对其进行了多次细化。同时，一旦自由度被集合起来， <code>SineGordonProblem</code> 类的所有矩阵和向量成员都被初始化为相应的大小。像 step-24 一样，我们使用 <code>MatrixCreator</code> 函数来生成质量矩阵 $M$ 和拉普拉斯矩阵 $A$ ，并在程序的剩余时间里将它们存储在适当的变量中。\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// 这个函数为牛顿方法的每次迭代组装系统矩阵和右手向量。关于系统矩阵和右手边的明确公式，读者应该参考导论。\n\n// 请注意，在每个时间步长中，我们必须把对矩阵和右手边的各种贡献加起来。与 step-23 和 step-24 相比，这需要集合更多的项，因为它们取决于前一个时间步骤或前一个非线性步骤的解。我们使用函数 <code>compute_nl_matrix</code> 和 <code>compute_nl_term</code> 来做到这一点，而本函数提供了顶层逻辑。\n\n  template <int dim> \n  void SineGordonProblem<dim>::assemble_system() \n  { \n\n// 首先我们组装雅各布矩阵 $F'_h(U^{n,l})$  ，其中 $U^{n,l}$ 为方便起见被储存在向量 <code>solution</code> 中。\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// 接下来我们计算右手边的向量。这只是介绍中对 $-F_h(U^{n,l})$ 的描述所暗示的矩阵-向量的组合。\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// 这个函数计算向量 $S(\\cdot,\\cdot)$ ，它出现在分裂公式的两个方程的非线性项中。这个函数不仅简化了这个项的重复计算，而且也是我们在时间步长为隐式时使用的非线性迭代求解器的基本组成部分（即 $\\theta\\ne 0$  ）。此外，我们必须允许该函数接收一个 \"旧 \"和一个 \"新 \"的解决方案作为输入。这些可能不是存储在 <code>old_solution</code> and <code>solution</code> 中的问题的实际解决方案，而只是我们线性化的两个函数。为了这个函数的目的，让我们在下面这个类的文档中分别调用前两个参数  $w_{\\mathrm{old}}$  和  $w_{\\mathrm{new}}$  。\n\n// 作为一个旁注，也许值得研究一下什么阶次的正交公式最适合这种类型的积分。由于 $\\sin(\\cdot)$ 不是一个多项式，可能没有正交公式可以准确地积分这些项。通常只需确保右手边的积分达到与离散化方案相同的精度即可，但通过选择更精确的正交公式，也许可以改善渐近收敛声明中的常数。\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// 一旦我们将 <code>FEValues</code> 实例化重新初始化到当前单元格，我们就利用 <code>get_function_values</code> 例程来获取 \"旧 \"数据（大概在 $t=t_{n-1}$ ）和 \"新 \"数据（大概在 $t=t_n$ ）在所选正交公式节点的值。\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// 现在，我们可以用所需的正交公式来评估  $\\int_K \\sin\\left[\\theta w_{\\mathrm{new}} + (1-\\theta) w_{\\mathrm{old}}\\right] \\,\\varphi_j\\,\\mathrm{d}x$  。\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// 我们通过将各单元的积分对全局积分的贡献相加来得出结论。\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// 这是处理非线性方案的第二个函数。它计算矩阵  $N(\\cdot,\\cdot)$  ，它出现在  $F(\\cdot)$  的雅各布项的非线性项中。正如 <code>compute_nl_term</code> 一样，我们必须让这个函数接收一个 \"旧 \"和一个 \"新 \"的解决方案作为输入，我们再次将其分别称为 $w_{\\mathrm{old}}$ 和 $w_{\\mathrm{new}}$ ，如下。\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// 同样，首先我们将我们的 <code>FEValues</code> 实例化重新初始化为当前单元。\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// 然后，我们用所需的正交公式评估 $\\int_K \\cos\\left[\\theta w_{\\mathrm{new}} + (1-\\theta) w_{\\mathrm{old}}\\right]\\, \\varphi_i\\, \\varphi_j\\,\\mathrm{d}x$ 。\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// 最后，我们将各单元的积分对全局积分的贡献相加。\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// 正如在介绍中所讨论的，这个函数在线性方程组上使用CG迭代求解器，该方程组是由牛顿方法的每个迭代的有限元空间离散化产生的，用于分割公式中的（非线性）第一个方程。该系统的解实际上是 $\\delta U^{n,l}$ ，所以它被存储在 <code>solution_update</code> and used to update <code>solution</code> 的 <code>run</code> 函数中。\n\n// 注意，我们在求解前将解的更新值重新设置为零。这是没有必要的：迭代求解器可以从任何一点开始并收敛到正确的解。如果对线性系统的解有一个很好的估计，那么从这个向量开始可能是值得的，但是作为一个一般的观察，起点并不是很重要：它必须是一个非常非常好的猜测，以减少超过几个迭代的次数。事实证明，对于这个问题，使用之前的非线性更新作为起点实际上会损害收敛性并增加所需的迭代次数，所以我们简单地将其设置为零。\n\n// 该函数返回收敛到一个解决方案所需的迭代次数。这个数字以后将被用来在屏幕上生成输出，显示每次非线性迭代需要多少次迭代。\n\n  template <int dim> \n  unsigned int SineGordonProblem<dim>::solve() \n  { \n    SolverControl            solver_control(1000, 1e-12 * system_rhs.l2_norm()); \n    SolverCG<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// 这个函数将结果输出到一个文件。它与  step-23  和  step-24  中的相应函数基本相同。\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// 这个函数对一切都有最高级别的控制：它运行（外部）时间步长循环，（内部）非线性求解器循环，并在每个时间步长后输出解。\n\n  template <int dim> \n  void SineGordonProblem<dim>::run() \n  { \n    make_grid_and_dofs(); \n\n// 为了确认初始条件，我们必须使用函数  $u_0(x)$  来计算  $U^0$  。为此，下面我们将创建一个 <code>InitialValues</code> 类型的对象；注意，当我们创建这个对象（它来自 <code>Function</code> 类）时，我们将其内部的时间变量设置为 $t_0$ ，以表明初始条件是在 $t=t_0$ 处评估的空间和时间的函数。\n\n// 然后我们通过使用 <code>VectorTools::project</code> 将 $u_0(x)$ 投影到网格上，产生 $U^0$ 。我们必须使用与 step-21 相同的悬挂节点约束结构： VectorTools::project 函数需要一个悬挂节点约束对象，但为了使用它，我们首先需要关闭它。\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// 为了完整起见，我们像其他时间步长一样，将第2个时间步长输出到一个文件。\n\n    output_results(0); \n\n// 现在我们进行时间步进：在每个时间步进中，我们解决与问题的有限元离散化相对应的矩阵方程，然后根据我们在介绍中讨论的时间步进公式推进我们的解决方案。\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// 在每个时间步长的开始，我们必须通过牛顿方法求解拆分公式中的非线性方程---即先求解 $\\delta U^{n,l}$ ，然后再计算 $U^{n,l+1}$ ，如此反复。这种非线性迭代的停止标准是： $\\|F_h(U^{n,l})\\|_2 \\le 10^{-6} \\|F_h(U^{n,0})\\|_2$  。因此，我们需要记录第一次迭代中残差的规范。\n\n// 在每次迭代结束时，我们向控制台输出我们花了多少次线性求解器的迭代。当下面的循环完成后，我们有（一个近似的） $U^n$  。\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// 在得到问题的第一个方程 $t=t_n$ 的解后，我们必须更新辅助速度变量  $V^n$  。然而，我们不计算和存储 $V^n$ ，因为它不是我们在问题中直接使用的数量。因此，为了简单起见，我们直接更新 $MV^n$ 。\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// 很多时候，特别是对于细网格，我们必须选择相当小的时间步长，以使方案稳定。因此，有很多时间步长，在解的过程中 \"没有什么有趣的事情发生\"。为了提高整体效率--特别是加快程序速度和节省磁盘空间--我们每隔 <code>output_timestep_skip</code> 个时间步数才输出解。\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// 这是该程序的主函数。它创建一个顶层类的对象并调用其主函数。如果在执行 <code>SineGordonProblem</code> 类的运行方法时抛出了异常，我们会在这里捕获并报告它们。关于异常的更多信息，读者应该参考  step-6  。\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": "//\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": "#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": "#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": "/* 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": "/**\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// 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": "//=======================================================================\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//\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// 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": "#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 << \"一共找到了\" << matches.size() << \"组匹配点\" << 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": "#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": "/*\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": "#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": "#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": "#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": "// -*- 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": "#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": "//\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 \"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|                     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": "//=======================================================================\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": "#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": "/*\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": "#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": "// [[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": "// 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/*!\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": "/*\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 * @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": "/*\n * Copyright (c) 2010-2012 Steffen Kieß\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": "#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": "// 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": "#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": "/**************************************************************************\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": "/**\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": "#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": "#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": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\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 \"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": "﻿//***********************************************************\r\n// 17/10/2020\t1.0.0\tRémi 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[Τᴴ¹] = 2.9;\r\n\t\tm_P[Τᴴ²] = 19.1;\r\n\t\tm_P[delta] = 45;\r\n\t\tm_P[μ1] = 239.6;\r\n\t\tm_P[ѕ1] = 41.4;\r\n\t\tm_P[μ2] = 876.0;\r\n\t\tm_P[ѕ2] = 55.6;\r\n\t\tm_P[μ3] = 625.2;\r\n\t\tm_P[ѕ3] = 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[μ1], m_P[ѕ1]);\r\n\t\tboost::math::logistic_distribution<double> emerge_dist2(m_P[μ2], m_P[ѕ2]);\r\n\t\tboost::math::logistic_distribution<double> emerge_dist3(m_P[μ3], m_P[ѕ3]);\r\n\t\t//boost::math::logistic_distribution<double> emerge_dist4(m_P[μ4], m_P[ѕ4]);\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[Τᴴ¹], m_P[Τᴴ²]);\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[Τᴴ¹], m_P[Τᴴ²]);\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[Τᴴ¹] >= m_P[Τᴴ²])\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[ʎ0]); 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[ʎa], T), ROUND_VAL);\r\n\r\n\t//\t\tdouble DD = min(0.0, T - m_ADE[ʎb]);//DD is negative\r\n\r\n\t//\t\t//if (ii < m_ADE[ʎ0])\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[ʎ2], m_ADE[ʎ3]);\r\n\t//\tint begin = (int)Round(m_ADE[ʎ0] + m_ADE[ʎ1] * 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[μ], m_P[ѕ]);\r\n\r\n\r\n\r\n\t\t//boost::math::weibull_distribution<double> emerge_dist(m_P[μ], m_P[ѕ]);\r\n\t\t//boost::math::beta_distribution<double> emerge_dist(m_P[μ], m_P[ѕ]);\r\n\t\t//boost::math::exponential_distribution<double> emerge_dist(m_P[ѕ]);\r\n\t\t//boost::math::rayleigh_distribution<double> emerge_dist(m_P[ѕ]);\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[μ1], m_P[ѕ1], m_P[μ1], m_P[ѕ1]} };\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[μ1 + 2 * s];\r\n\t\t\tdouble S = m_P[ѕ1 + 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": "//==================================================================================================\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": "// 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": "/* 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–672 (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 (µs)\"   << 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": "/*\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": "/*\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 * λ^n : ∀(r) ∈ 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            /* λ[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] * λ[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 ∈ row(P(D^n)), b ∈ 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] = ∑ 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": "#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": "/*****************************************************************************\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//  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;                            // 成像点到圆心的距离\n    unsigned long long pre_malloc_points_per_triangle; // 预先用来保存单个三角形点坐标的空间大小\n    uint16_t point_sum_per_line;                       // 成像点每行的个数，图为正方形\n    float coord_step;                                  // 当前成像分辨率下坐标标准方向上的步进\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]; //振元坐标\n    float *triangle_vertex_x, *triangle_vertex_y;               // 所有三角形顶点坐标\n    unsigned long long temp_sample_points_coords_cnt[ELE_NO];        //每个发射源扫描区的点数\n    uint16_t **temp_sample_points_coords;              // 二维数组[ELE_NO][采样点数]\n    void calc_all_sample_points_coords(int thread_sum);         // 多线程计算所有扫描区中，点的坐标\n    void save_all_triangles(int thread_sum);                    // 多线程保存文件\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 是成像分辨率单维点数\nvoid Coord_Process::initialize(uint16_t num) {\n    dis_farest_point = RADIUS - 0.01; // 距离探头 10mm 的不成像\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// 计算所有发射源的坐标\nvoid Coord_Process::calc_ele_coords() {\n    float raduis = RADIUS;\n    float ele_angle_offset = (2 * PI * 43.4695 / (256 - 1)) / 360; //阵元间隔角度\n    float start_ele_angle = 2 * PI * (45 - 43.4695) / 360;         //第一个阵元角度\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    // 把上面的 for 循环融入到下面会产生误差，但是上面的结果不符合可90度旋转原理\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// 计算所有发射源扫描区(三角形)的三点坐标\nvoid Coord_Process::calc_all_triangles() {\n    float radius = RADIUS;\n    float temp_point[3][2];   // 3个点，每个点2个坐标值\n    uint16_t high_id, low_id; // 最高点和最低点的 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        // 排序\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// 把三角形三点坐标转移到整数空间\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// 扫描单个三角形中的点\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// 多线程扫描所有的(2048)三角形，thread_sum 通过进程参数设置\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// 打印所有探头的坐标\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": "#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": "/**\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 \"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 \"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": "// 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": "/*\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// 这个程序开始时和其他大多数程序一样，有众所周知的包含文件。与 step-15 程序相比，我们在这里所做的大部分工作都是从该程序中复制的，唯一不同的是包括头文件，我们从该文件中导入了SparseDirectUMFPACK类和KINSOL的实际接口。\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// 同样地，这个程序的主类基本上是  step-15  中的一个副本。然而，该类确实将雅各布（系统）矩阵（以及使用直接求解器对其进行因式分解）和残差的计算分成了不同的函数，原因已在介绍中列出。出于同样的原因，该类也有一个指向雅各布矩阵因式分解的指针，该指针在我们每次更新雅各布矩阵时被重置。\n\n// （如果你想知道为什么程序对雅各布矩阵使用直接对象，而对因式分解使用指针。每次KINSOL要求更新雅各布矩阵时，我们可以简单地写`jacobian_matrix=0;`将其重置为一个空矩阵，然后我们可以再次填充。另一方面，SparseDirectUMFPACK类没有办法扔掉它的内容或用新的因式分解来替换它，所以我们使用一个指针。我们只是扔掉整个对象，并在我们有新的雅各布矩阵需要分解时创建一个新的对象。)\n\n// 最后，该类有一个定时器变量，我们将用它来评估程序的不同部分需要多长时间，这样我们就可以评估KINSOL的不重建矩阵及其因式分解的倾向是否合理。我们将在下面的 \"结果 \"部分讨论这个问题。\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// 实现边界值的类是对  step-15  的复制。\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// 下面的几个函数也基本上是复制了 step-15 已经做的事情，所以没有什么可讨论的。\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// 然后，下面的函数负责对雅各布矩阵进行组装和因子化。该函数的前半部分实质上是 step-15 的`assemble_system()`函数，只是它没有处理同时形成右手边的向量（即残差），因为我们并不总是要同时做这些操作。\n\n// 我们把整个装配功能放在一个由大括号包围的代码块中，这样我们就可以用一个 TimerOutput::Scope 变量来衡量在这个代码块中花费了多少时间，不包括在这个函数中发生在匹配的闭合括号`}`之后的一切。\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// 该函数的后半部分是对计算出的矩阵进行因数分解。为此，我们首先创建一个新的SparseDirectUMFPACK对象，并将其分配给成员变量`jacobian_matrix_factorization`，同时销毁该指针之前指向的任何对象（如果有）。然后我们告诉该对象对雅各布系数进行分解。\n\n// 如上所述，我们把这段代码放在大括号里，用一个计时器来评估这部分程序所需的时间。\n\n// (严格来说，我们在这里完成后实际上不再需要矩阵了，我们可以把矩阵对象扔掉。一个旨在提高内存效率的代码会这样做，并且只在这个函数中创建矩阵对象，而不是作为周围类的成员变量。我们在这里省略了这一步，因为使用与以前的教程程序相同的编码风格可以培养对通用风格的熟悉，并有助于使这些教程程序更容易阅读)。\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()`在 step-15 中用来做的第二部分是计算残差向量，也就是牛顿线性系统的右手向量。我们把这一点从前面的函数中分解出来，但如果你理解了 step-15 中`assemble_system()`的作用，下面的函数就会很容易理解。然而，重要的是，我们需要计算的残差不是围绕当前解向量线性化的，而是我们从KINSOL得到的任何东西。这对于诸如直线搜索这样的操作是必要的，我们想知道在不同的 $\\alpha_k$ 值下，残差 $F(U^k + \\alpha_k \\delta U^K)$ 是多少；在这些情况下，KINSOL只是给我们函数 $F$ 的参数，然后我们在这时计算残差 $F(\\cdot)$ 。\n\n// 该函数在最后打印出如此计算的残差的规范，作为我们跟踪程序进展的一种方式。\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// 接下来是实现用雅各布矩阵解线性系统的函数。由于我们在建立矩阵时已经对矩阵进行了因式分解，所以解决线性系统的方法就是将逆矩阵应用于给定的右侧向量。这就是我们在这里使用的 SparseDirectUMFPACK::vmult() 函数的作用。在这之后，我们必须确保我们也能解决解向量中的悬空节点的值，而这是用 AffineConstraints::distribute(). 来完成的。\n\n// 该函数需要一个额外的，但未使用的参数`tolerance`，它表示我们必须解决线性系统的精确程度。这个参数的含义在介绍中结合 \"Eisenstat Walker技巧 \"进行了讨论，但由于我们使用的是直接求解器而不是迭代求解器，所以我们并没有利用这个机会只求解线性系统的不精确性。\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// 以下三个函数又是对  step-15  中的函数的简单复制。\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// 这个程序中唯一**有趣的函数是驱动整个算法的函数，即从一个粗大的网格开始，做一些网格细化循环，并在每个网格上使用KINSOL来寻找我们从这个网格上离散化得到的非线性代数方程的解。上面的`refine_mesh()`函数可以确保一个网格上的解被用作下一个网格的起始猜测。我们还使用一个TimerOutput对象来测量每个网格上的每一次操作所花费的时间，并在每个周期开始时重置该计时器。\n\n// 正如在介绍中所讨论的，没有必要特别精确地解决粗略网格上的问题，因为这些问题只能作为下一个网格的起始猜测来解决。因此，我们将在 $k$ 个网格细化周期中使用 $\\tau=10^{-3} \\frac{1}{10^k}$ 的目标公差。\n\n// 所有这些都在这个函数的第一部分进行了编码。\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// 这就是有趣的开始。在顶部，我们创建了KINSOL求解器对象，并给它提供了一个对象，该对象编码了一些额外的具体情况（其中我们只改变了我们想要达到的非线性容忍度；但你可能想看看 SUNDIALS::KINSOL::AdditionalData 类有哪些其他成员，并与它们一起玩）。\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// 然后，我们必须描述在介绍中已经提到的操作。从本质上讲，我们必须教KINSOL如何(i)将一个向量调整到正确的大小，(ii)计算残差向量，(iii)计算雅各布矩阵（在这期间我们也计算其因式分解），以及(iv)用雅各布矩阵解一个线性系统。\n\n// 所有这四种操作都由 SUNDIALS::KINSOL 类的成员变量表示，这些成员变量的类型是 `std::function`, ，即它们是我们可以分配给一个函数的指针的对象，或者像我们在这里做的那样，一个 \"lambda函数\"，它接受相应的参数并返回相应的信息。按照惯例，KINSOL希望做一些不重要的事情的函数返回一个整数，其中0表示成功。事实证明，我们只需用25行代码就可以完成所有这些工作。\n\n// 如果你不知道什么是 \"lambda函数\"，可以看看 step-12 或[wikipedia页面](https:en.wikipedia.org/wiki/Anonymous_function)关于这个问题。lambda函数的想法是，人们想用一组参数来定义一个函数，但(i)不使它成为一个命名的函数，因为通常情况下，该函数只在一个地方使用，似乎没有必要给它一个全局名称；(ii)该函数可以访问存在于定义它的地方的一些变量，包括成员变量。lambda函数的语法很笨拙，但最终还是很有用的）。)\n\n// 在代码块的最后，我们告诉KINSOL去工作，解决我们的问题。从'residual'、'setup_jacobian'和'solve_jacobian_system'函数中调用的成员函数将向屏幕打印输出，使我们能够跟踪程序的进展情况。\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// 剩下的就只是内务整理了。将数据写入文件，以便进行可视化，并显示收集到的时间摘要，以便我们可以解释每个操作花了多长时间，执行的频率如何，等等。\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 * \\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": "/*\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": "#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": "\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": "/**\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 “UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction“, 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// 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": "/*\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": "// 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éphane 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 * 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": "#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 <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": "/*\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": "/* -------------------------------------------------------------------------\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": "#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": "#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": "#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": "#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\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": "// 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": "/*\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 © 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": "///////////////////////////////////////////////////////////////////////////////\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": "\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": "#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// β-detected nuclear magnetic resonance (β-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": "#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": "/*!\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": "// 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) 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": "/* -*- 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": "// 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": "// 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//     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// 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 \"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": "#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": "/// @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": "#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 <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": "#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": "#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// 前面几个文件已经在前面的例子中讲过了，因此不再做进一步的评论。\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// 我们将在牛顿迭代之间使用自适应网格细化技术。要做到这一点，我们需要能够在新的网格上使用解决方案，尽管它是在旧的网格上计算出来的。SolutionTransfer类将解决方案从旧网格转移到新网格。\n\n#include <deal.II/numerics/solution_transfer.h> \n\n// 然后，我们为这个程序打开一个命名空间，像以前的程序一样，将dealii命名空间中的所有东西导入其中。\n\nnamespace Step15 \n{ \n  using namespace dealii; \n// @sect3{The <code>MinimalSurfaceProblem</code> class template}  \n\n// 类模板与  step-6  中的基本相同。 增加了三个内容。\n\n// - 有两个解决方案向量，一个用于牛顿更新  $\\delta u^n$  ，另一个用于当前迭代  $u^n$  。\n\n// -  <code>setup_system</code> 函数需要一个参数，表示这是否是第一次被调用。不同的是，第一次我们需要分配自由度，并将 $u^n$ 的解向量设置为正确的大小。接下来的几次，该函数是在我们已经完成了这些步骤，作为细化 <code>refine_mesh</code> 中网格的一部分之后被调用的。\n\n// - 然后我们还需要新的函数。  <code>set_boundary_values()</code> 负责正确设置解向量的边界值，这在介绍的最后已经讨论过了。  <code>compute_residual()</code> 是一个计算非线性（离散）残差规范的函数。我们用这个函数来监测牛顿迭代的收敛性。该函数以步长 $\\alpha^n$ 为参数来计算 $u^n + \\alpha^n \\; \\delta u^n$ 的残差。这是人们通常需要的步长控制，尽管我们在这里不会使用这个功能。最后， <code>determine_step_length()</code> 计算每个牛顿迭代中的步长 $\\alpha^n$ 。正如介绍中所讨论的，我们在这里使用一个固定的步长，并把实现一个更好的策略作为一个练习。(  step-77 的做法不同。它只是在整个求解过程中使用了一个外部包，而一个好的直线搜索策略是该包所提供的一部分）。)\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// 边界条件的实现就像在  step-4  中一样。 它被选为  $g(x,y)=\\sin(2 \\pi (x+y))$  。\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// 该类的构造函数和析构函数与前几篇教程中的相同。\n\n  template <int dim> \n  MinimalSurfaceProblem<dim>::MinimalSurfaceProblem() \n    : dof_handler(triangulation) \n    , fe(2) \n  {} \n// @sect4{MinimalSurfaceProblem::setup_system}  \n\n// 在setup-system函数中，我们总是设置有限元方法的变量。与 step-6 有相同的区别，因为在那里我们在每个细化周期中都要从头开始求解PDE，而在这里我们需要把以前的网格的解放到当前的网格上。因此，我们不能只是重置解向量。因此，传递给这个函数的参数表明我们是否可以分布自由度（加上计算约束）并将解向量设置为零，或者这在其他地方已经发生过了（特别是在 <code>refine_mesh()</code> ）。\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// 该函数的其余部分与  step-6  中的相同。\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// 这个函数的作用与前面的教程相同，当然，现在矩阵和右手边的函数取决于上一次迭代的解。正如在介绍中所讨论的，我们需要使用牛顿更新的零边界值；我们在这个函数的最后计算它们。\n\n// 该函数的顶部包含了通常的模板代码，设置了允许我们在正交点评估形状函数的对象，以及本地矩阵和向量的临时存储位置，以及正交点上先前解的梯度。然后我们开始在所有单元格上进行循环。\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// 为了组装线性系统，我们必须在正交点上获得前一个解的梯度值。有一个标准的方法： FEValues::get_function_gradients 函数接收一个代表定义在DoFHandler上的有限元场的向量，并评估这个场在FEValues对象最后被重新初始化的单元的正交点的梯度。然后将所有正交点的梯度值写入第二个参数中。\n\n        fe_values.get_function_gradients(current_solution, \n                                         old_solution_gradients); \n\n// 有了这个，我们就可以对所有的正交点和形状函数进行积分循环。 在刚刚计算了正交点中旧解的梯度后，我们就可以计算这些点中的系数 $a_{n}$ 。 然后，系统本身的组装看起来与我们一贯的做法相似，除了非线性项之外，将结果从局部对象复制到全局对象中也是如此。\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// 最后，我们从系统中移除悬挂的节点，并将零边界值应用到定义牛顿更新的线性系统中  $\\delta u^n$  。\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// 解算函数和以往一样。在求解过程的最后，我们通过设置 $u^{n+1}=u^n+\\alpha^n\\;\\delta u^n$ 来更新当前的解决方案。\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// 这个函数的第一部分与 step-6 中的内容相同 ... 然而，在细化网格后，我们必须将旧的解决方案转移到新的解决方案中，我们在SolutionTransfer类的帮助下完成。这个过程稍微有点复杂，所以让我们详细描述一下。\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 函数来实现。 这个函数标志着一组额外的单元格进行细化或粗化，以执行像单悬节点规则这样的规则。 调用此函数后，被标记为细化和粗化的单元格正是那些将被实际细化或粗化的单元格。通常情况下，你不需要手工操作 (Triangulation::execute_coarsening_and_refinement 为你做这个）。) 然而，我们需要初始化SolutionTransfer类，它需要知道最终将被粗化或细化的单元集，以便存储旧网格的数据并转移到新网格。因此，我们手动调用这个函数。\n\n    triangulation.prepare_coarsening_and_refinement(); \n\n// 有了这个方法，我们用现在的DoFHandler初始化一个SolutionTransfer对象，并将解决方案向量附加到它上面，然后在新网格上进行实际的细化和自由度分配\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// 最后，我们找回插值到新网格的旧解。由于SolutionTransfer函数实际上并不存储旧的解决方案的值，而是索引，我们需要保留旧的解决方案向量，直到我们得到新的内插值。因此，我们将新的数值写入一个临时的向量中，之后才将其写入解决方案向量对象中。\n\n    Vector<double> tmp(dof_handler.n_dofs()); \n    solution_transfer.interpolate(current_solution, tmp); \n    current_solution = tmp; \n\n// 在新的网格上，有不同的悬挂节点，对于这些节点，我们必须在扔掉之前的对象内容后，重新计算约束。为了安全起见，我们还应该确保当前解决方案的向量条目满足悬空节点的约束条件（参见SolutionTransfer类文档中的讨论，了解为什么必须这样做）。我们可以通过明确调用`hanging_node_constraints.distribution(current_solution)`来做到这一点；我们省略这一步，因为这将在下面调用`set_boundary_values()`的最后发生，而且没有必要做两次。\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// 一旦我们有了内插的解决方案和所有关于悬挂节点的信息，我们必须确保我们现在的 $u^n$ 实际上有正确的边界值。正如在介绍的最后所解释的，即使细化前的解决方案有正确的边界值，也不会自动出现这种情况，因此我们必须明确地确保它现在有。\n\n    set_boundary_values(); \n\n// 我们通过更新所有剩余的数据结构来结束这个函数，向 <code>setup_dofs()</code> 表明这不是第一次了，它需要保留解向量的内容。\n\n    setup_system(false); \n  } \n\n//  @sect4{MinimalSurfaceProblem::set_boundary_values}  \n\n// 下一个函数确保解向量的条目尊重我们问题的边界值。 在细化了网格之后（或者刚刚开始计算），边界上可能会出现新的节点。这些节点的数值是在`refine_mesh()`中从之前的网格中简单插值出来的，而不是正确的边界值。这个问题可以通过将当前解决方案向量的所有边界节点明确设置为正确的值来解决。\n\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 (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// 为了监测收敛性，我们需要一种方法来计算（离散）残差的规范，即在介绍中讨论的向量 $\\left<F(u^n),\\varphi_i\\right>$ 与 $F(u)=-\\nabla \\cdot \\left(\\frac{1}{\\sqrt{1+|\\nabla u|^{2}}}\\nabla u \\right)$ 的规范。事实证明，（尽管我们在当前版本的程序中没有使用这个功能）在确定最佳步长时需要计算残差 $\\left<F(u^n+\\alpha^n\\;\\delta u^n),\\varphi_i\\right>$ ，因此这就是我们在这里实现的：该函数将步长 $\\alpha^n$ 作为参数。原有的功能当然是通过传递一个零作为参数得到的。\n\n// 在下面的函数中，我们首先为残差设置一个向量，然后为评估点设置一个向量  $u^n+\\alpha^n\\;\\delta u^n$  。接下来是我们在所有的积分操作中使用的相同的模板代码。\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// 实际的计算与  <code>assemble_system()</code>  中的计算差不多。我们首先评估 $u^n+\\alpha^n\\,\\delta u^n$ 在正交点的梯度，然后计算系数 $a_n$ ，然后将其全部插入残差公式中。\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// 在这个函数的最后，我们还必须处理悬挂节点的约束和边界值的问题。关于后者，我们必须将所有对应于位于边界的自由度的条目的残差向量元素设置为零。原因是，由于那里的解的值是固定的，它们当然不是 \"真正的 \"自由度，因此，严格来说，我们不应该在残差向量中为它们集合条目。然而，正如我们一直所做的那样，我们想在每个单元上做完全相同的事情，因此我们并不想在上面的积分中处理某个自由度是否位于边界的问题。相反，我们将简单地在事后将这些条目设置为零。为此，我们需要确定哪些自由度实际上属于边界，然后在所有这些自由度上进行循环，并将剩余条目设置为零。这发生在以下几行中，我们已经在 step-11 中看到了使用DoFTools命名空间的适当函数。\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// 在函数的最后，我们返回残差的常数。\n\n    return residual.l2_norm(); \n  } \n\n//  @sect4{MinimalSurfaceProblem::determine_step_length}  \n\n// 正如介绍中所讨论的，如果我们总是采取全步，即计算 $u^{n+1}=u^n+\\delta u^n$ ，牛顿方法经常不收敛。相反，我们需要一个阻尼参数（步长）  $\\alpha^n$  并设置  $u^{n+1}=u^n+\\alpha^n\\delta u^n$  。这个函数是用来计算 $\\alpha^n$  的。\n\n// 在这里，我们简单地总是返回0.1。这当然是一个次优的选择：理想情况下，人们希望的是，当我们越来越接近解的时候，步长变成1，这样我们就可以享受牛顿方法的快速二次收敛。我们将在下面的结果部分讨论更好的策略， step-77 也涉及这方面的内容。\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// 从`run()`调用的最后一个函数以图形形式输出当前的解决方案（和牛顿更新），作为VTU文件。它与之前教程中使用的完全相同。\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// 在运行函数中，我们建立第一个网格，然后有牛顿迭代的顶层逻辑。\n\n// 正如在介绍中所描述的，领域是围绕原点的单位圆盘，创建方式与 step-6 中所示相同。网格经过两次全局细化，然后再进行若干次适应性循环。\n\n// 在开始牛顿循环之前，我们还需要做一些设置工作。我们需要创建基本的数据结构，并确保第一个牛顿迭代已经有了正确的边界值，这在介绍中已经讨论过了。\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// 接下来开始牛顿迭代。我们一直迭代到上一次迭代结束时计算的残差（规范）小于 $10^{-3}$ ，正如在 \"do{ ... } while \"循环结束时的检查。因为我们没有一个合理的值来初始化这个变量，所以我们只是使用可以表示为`双数'的最大值。\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// 在每个网格上，我们正好做五个牛顿步骤。我们在这里打印初始残差，然后在这个网格上开始迭代。\n\n// 在每一个牛顿步骤中，首先要计算系统矩阵和右手边，然后我们存储右手边的规范作为残差，以便在决定是否停止迭代时进行检查。然后我们求解线性系统（该函数也会更新 $u^{n+1}=u^n+\\alpha^n\\;\\delta u^n$ ），并在这个牛顿步骤结束时输出残差的准则。\n\n// 在这个循环结束后，我们还将以图形形式输出当前网格上的解，并增加网格细化循环的计数器。\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// 最后是主函数。这遵循了所有其他主函数的方案。\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": "// 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": "\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// 同样，前几个include文件已经知道了，所以我们不会对它们进行评论。\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// 这些，现在，是多级方法所必需的包括。第一个声明了如何处理多网格方法每个层次上的Dirichlet边界条件。对于自由度的实际描述，我们不需要任何新的包含文件，因为DoFHandler已经实现了所有必要的方法。我们只需要将自由度分配给更多的层次。\n\n// 其余的包含文件涉及到作为线性算子（求解器或预处理器）的多重网格的力学问题。\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// 最后我们包括MeshWorker框架。这个框架通过其函数loop()和integration_loop()，自动在单元格上进行循环，并将数据组装成向量、矩阵等。它自动服从约束。由于我们必须建立几个矩阵，并且必须注意几组约束，这将使我们省去很多麻烦。\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// 为了节省精力，我们使用了在以下文件中找到的预先实现的拉普拉斯。\n\n#include <deal.II/integrators/laplace.h> \n#include <deal.II/integrators/l2.h> \n\n// 这就是C++。\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() 希望有一个类能够提供在单元格和边界及内部面的积分功能。这是由下面的类来完成的。在构造函数中，我们告诉循环应该计算单元格积分（\"真\"），但不应该计算边界和内部面的积分（两个 \"假\"）。因此，我们只需要一个单元格函数，而不需要面的函数。\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// 接下来是每个单元上的实际积分器。我们解决一个泊松问题，在右半平面上的系数为1，在左半平面上的系数为十分之一。\n\n//  MeshWorker::LocalResults 的基类 MeshWorker::DoFInfo 包含可以在这个局部积分器中填充的对象。在MeshWorker框架内，有多少对象被创建是由装配器类决定的。在这里，我们举例测试一下，需要一个矩阵 (MeshWorker::LocalResults::n_matrices()).  矩阵是通过 MeshWorker::LocalResults::matrix(), 来访问的，它的第一个参数是矩阵的编号。第二个参数只用于面的积分，当每个测试函数使用两个矩阵时。那么，第二个指标为 \"true \"的矩阵将以相同的索引存在。\n\n//  MeshWorker::IntegrationInfo 提供了一个或几个FEValues对象，下面这些对象被 LocalIntegrators::Laplace::cell_matrix() 或 LocalIntegrators::L2::L2(). 使用，因为我们只组装一个PDE，所以也只有一个索引为0的对象。\n\n// 此外，我们注意到这个积分器的作用是计算多级预处理的矩阵，以及全局系统的矩阵和右手边。由于系统的汇编器需要一个额外的向量， MeshWorker::LocalResults::n_vectors() 要返回一个非零值。相应地，我们在这个函数的末尾填充了一个右边的向量。由于LocalResults可以处理多个BlockVector对象，但我们这里又是最简单的情况，所以我们将信息输入到零号向量的零号块中。\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// 这个主类与  step-6  中的类基本相同。就成员函数而言，唯一增加的是 <code>assemble_multigrid</code> 函数，它组装了对应于中间层离散运算符的矩阵。\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// 以下成员是多网格方法的基本数据结构。前两个表示稀疏模式和多级层次结构中各个层次的矩阵，非常类似于上面的全局网格的对象。\n\n// 然后，我们有两个新的矩阵，只需要在自适应网格上进行局部平滑的多网格方法。它们在细化区域的内部和细化边缘之间传递数据，在 @ref mg_paper \"多网格论文 \"中详细介绍过。\n\n// 最后一个对象存储了每个层次上的边界指数信息和位于两个不同细化层次之间的细化边缘上的指数信息。因此，它的作用与AffineConstraints类似，但在每个层次上。\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// 关于三角形的构造函数只有一个简短的评论：按照惯例，deal.II中所有自适应精化的三角形在单元格之间的面的变化不会超过一个级别。然而，对于我们的多网格算法，我们需要一个更严格的保证，即网格在连接两个单元的顶点上的变化也不超过细化级别。换句话说，我们必须防止出现以下情况。\n\n//  @image html limit_level_difference_at_vertices.png \"\"  \n\n// 这可以通过向三角化类的构造函数传递 Triangulation::limit_level_difference_at_vertices 标志来实现。\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// 除了只是在DoFHandler中分配自由度之外，我们在每一层都做同样的事情。然后，我们按照之前的程序，在叶子网格上设置系统。\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// 多网格约束必须被初始化。他们也需要知道边界值，所以我们也在这里传递 <code>dirichlet_boundary</code> 。\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// 现在是关于多网格数据结构的事情。首先，我们调整多级对象的大小，以容纳每一级的矩阵和稀疏模式。粗略的级别是零（现在是强制性的，但在未来的修订中可能会改变）。注意，这些函数在这里采取的是一个完整的、包容的范围（而不是一个起始索引和大小），所以最细的级别是 <code>n_levels-1</code>  。我们首先要调整容纳SparseMatrix类的容器的大小，因为它们必须在调整大小时释放它们的SparsityPattern才能被销毁。\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// 现在，我们必须在每个层面上提供一个矩阵。为此，我们首先使用 MGTools::make_sparsity_pattern 函数在每个层次上生成一个初步的压缩稀疏模式（关于这个主题的更多信息，请参见 @ref Sparsity 模块），然后把它复制到我们真正想要的那个层次上。下一步是用这些稀疏模式初始化两种层次矩阵。\n\n// 值得指出的是，界面矩阵只有位于较粗的网格和较细的网格之间的界面上的自由度条目。因此，它们甚至比我们多网格层次结构中的各个层次的矩阵还要稀少。如果我们更关心内存的使用（可能还有我们使用这些矩阵的速度），我们应该对这两种矩阵使用不同的稀疏性模式。\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// 下面的函数将线性系统装配在网格的最细层上。由于我们想在下面的层次装配中重用这里的代码，我们使用本地积分器类LaplaceIntegrator，而将循环留给MeshWorker框架。因此，这个函数首先设置了这个框架所需的对象，即  \n\n// - 一个 MeshWorker::IntegrationInfoBox 对象，它将提供单元格上正交点的所有需要的数据。这个对象可以看作是FEValues的扩展，提供更多的有用信息。 \n\n// - 一个 MeshWorker::DoFInfo 对象，它一方面扩展了单元格迭代器的功能，另一方面也为其基类LocalResults的返回值提供了空间。 \n\n// - 一个汇编器，在这里是指整个系统。这里的 \"简单 \"指的是全局系统没有一个块状结构。 \n\n// - 本地集成器，它实现了实际的形式。\n\n// 在循环将所有这些组合成一个矩阵和一个右手边之后，还有一件事要做：集合器对受限自由度的矩阵行和列不做任何处理。因此，我们在对角线上放一个一，使整个系统摆好。一的值或任何固定的值都有一个好处，即它对矩阵的频谱的影响很容易理解。由于相应的特征向量形成了一个不变的子空间，所选择的值不会影响Krylov空间求解器的收敛性。\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// 下一个函数是建立线性算子（矩阵），定义每一级网格上的多栅方法。积分的核心和上面的一样，但是下面的循环会遍历所有已有的单元，而不仅仅是活动的单元，而且结果必须输入正确的层次矩阵。幸运的是，MeshWorker对我们隐藏了大部分的内容，因此这个函数和之前的函数的区别只在于汇编器的设置和循环中不同的迭代器。另外，最后修复矩阵的过程也比较复杂。\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// 这是另外一个在支持多栅求解器（或者说，事实上，我们使用多栅方法的前提条件）方面有明显不同的函数。\n\n// 让我们从建立多层次方法的两个组成部分开始：层次间的转移运算器和最粗层次上的求解器。在有限元方法中，转移算子来自所涉及的有限元函数空间，通常可以用独立于所考虑问题的通用方式计算。在这种情况下，我们可以使用MGTransferPrebuilt类，给定最终线性系统的约束和MGConstrainedDoFs对象，该对象知道每个层次的边界条件和不同细化层次之间接口的自由度，可以从具有层次自由度的DoFHandler对象中建立这些转移操作的矩阵。\n\n// 下面几行的第二部分是关于粗略网格求解器的。由于我们的粗网格确实非常粗，我们决定采用直接求解器（最粗层次矩阵的Householder分解），即使其实现不是特别复杂。如果我们的粗网格比这里的5个单元多得多，那么这里显然需要更合适的东西。\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// 多级求解器或预处理器的下一个组成部分是，我们需要在每一级上有一个平滑器。这方面常见的选择是使用松弛方法的应用（如SOR、Jacobi或Richardson方法）或求解器方法的少量迭代（如CG或GMRES）。 mg::SmootherRelaxation 和MGSmootherPrecondition类为这两种平滑器提供支持。这里，我们选择应用单一的SOR迭代。为此，我们定义一个适当的别名，然后设置一个平滑器对象。\n\n// 最后一步是用我们的水平矩阵初始化平滑器对象，并设置一些平滑参数。 <code>initialize()</code> 函数可以有选择地接受额外的参数，这些参数将被传递给每一级的平滑器对象。在当前SOR平滑器的情况下，这可能包括一个松弛参数。然而，我们在这里将这些参数保留为默认值。对 <code>set_steps()</code> 的调用表明我们将在每个级别上使用两个前平滑步骤和两个后平滑步骤；为了在不同级别上使用可变数量的平滑器步骤，可以在对 <code>mg_smoother</code> 对象的构造函数调用中设置更多选项。\n\n// 最后一步的结果是我们使用SOR方法作为平滑器的事实\n\n// --这不是对称的\n\n// 但我们在下面使用共轭梯度迭代（需要对称的预处理），我们需要让多级预处理确保我们得到一个对称的算子，即使是非对称的平滑器。\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// 下一个准备步骤是，我们必须将我们的水平矩阵和接口矩阵包裹在一个具有所需乘法函数的对象中。我们将为从粗到细的接口对象创建两个对象，反之亦然；多网格算法将在以后的操作中使用转置运算器，允许我们用已经建立的矩阵初始化该运算器的上下版本。\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// 现在，我们准备设置V型循环算子和多级预处理程序。\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// 有了这一切，我们终于可以用通常的方法来解决这个线性系统了。\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// 下面两个函数在计算出解决方案后对其进行后处理。特别是，第一个函数在每个周期开始时细化网格，第二个函数在每个周期结束时输出结果。这些函数与 step-6 中的函数几乎没有变化，只有一个小的区别：我们以VTK格式生成输出，以使用当今更现代的可视化程序，而不是 step-6 编写时的那些。\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// 和上面的几个函数一样，这几乎是对  step-6  中相应函数的复制。唯一的区别是对 <code>assemble_multigrid</code> 的调用，它负责形成我们在多网格方法中需要的每一层的矩阵。\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// 这又是与 step-6 中相同的函数。\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 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": "#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": "//==================================================================================================\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": "// -------------------------------------------------------------------\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—indeed, the key technique \n     * that allows us to track the decayed weights efficiently—is that they \n     * maintain counts and other quantities based on g(ti − L), and only scale \n     * by g(t − L) at query time. But while g(ti −L)/g(t−L) is guaranteed to \n     * lie between zero and one, the intermediate values of g(ti − 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 − 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(−α(L′ − L)), and obtain the correct value as if we had instead \n     * computed relative to a new landmark L′ (and then use this new L′ 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": "#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#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": "#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": "// 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": "/*\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": "\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": "#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": "/* -*- 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übertragung, 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": "#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": "// 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": "#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   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": "//  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": "/* -*- 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’s 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": "//\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": "//  (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 [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": "/* 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": "/* 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²([0,T], L²(Ω)) ∩ L²([0,T], H¹(Ω))\";\n}\n\ntemplate <int dim>\nstd::string H2L2PlusL2H1<dim>::unique_id() const {\n  return \"H²([0,T], L²(Ω)) ∩ L²([0,T], H¹(Ω)) with α=\" + std::to_string(alpha_) + \", β=\" + std::to_string(beta_) +\n         \", ɣ=\" + 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": "/********************************************************************************\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": "// 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": "//\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": "\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": "#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": "#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": "//  (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": "/**\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": "/*\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": "// 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änkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n// 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": "#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": "// 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 \"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": "#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": "\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": "// 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": "#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": "#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": "//---------------------------------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": "/**\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°);\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": "//\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<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": "/*\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": "//==============================================================================\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": "// 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 − 1, k − 2, . . . , k − m§\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 − m, k − m + 1, . . . , k − 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": "/// 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* 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": "#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 * 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": "//==============================================================================\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": "// 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": "//***************************************************************************\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": "#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": "#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    @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": "/*\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": "// 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²(t) = r²(t): v² t² + 2 vo t + o² = a²t² + 2 ar t + r²\n    // (v² - a²) t² + 2 (vo - ar)t + o² - r² = 0\n    // t² + 2 (vo - ar)/(v²-a²) t + (o²-r²)/(v²-a²) = 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ří 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": "\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": "/*=============================================================================\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": "/* 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": "#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// 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": "#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// 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": "#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": "/* +------------------------------------------------------------------------+\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": "#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": "\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": "#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": "//----------------------------------*-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": "#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": "// 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": "\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": "#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": "#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;    //列向量\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; //状态向量维度\n    const int input_dim;\n    const int measurement_dim, M; //测量向量维度\n\n    VectorXt mean;                //均值\n    MatrixXt cov;                 //协方差\n\n    System system;                //控制系统\n    MatrixXt process_noise;\t\t  //过程噪声 Q\n    MatrixXt measurement_noise;\t  //测量噪声 R\n\n    MatrixXt kalman_gain;         //卡尔曼增益K\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": "#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": "#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": "#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": "/*    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": "// =======================================================================\n// Copyright 2015 by Ireneusz Szcześniak\n// Author: Ireneusz Szcześniak <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": "//==================================================================================================\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": "#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 <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": "#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 * 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å 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øser differentialene vha octave-symbolic se ~/xoct/minsky/differentiate.\n// Transformerer octave-løsningene 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": "﻿#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": "/*\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": "//============================================================================\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": "#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": "#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": "\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// 在以前的教程程序中，特别是在 step-27 和 step-40 中，已经使用和讨论了以下包含文件。\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// 为了实现负载平衡，我们将在单元格上分配单独的权重，为此我们将使用类  parallel::CellWeights.  。\n#include <deal.II/distributed/cell_weights.h> \n\n// 求解函数需要从直角坐标到极坐标的转换。 GeometricUtilities::Coordinates 命名空间提供了必要的工具。\n\n#include <deal.II/base/function.h> \n#include <deal.II/base/geometric_utilities.h> \n\n// 以下包含的文件将启用MatrixFree功能。\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// 我们将使用 LinearAlgebra::distributed::Vector 进行线性代数操作。\n\n#include <deal.II/lac/la_parallel_vector.h> \n\n// 我们剩下的就是包含多网格求解器所需的文件。\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// 我们有一个分析性的方案可以使用。我们将用这个解来为问题的数值解施加边界条件。解决方案的表述需要转换为极坐标。为了从笛卡尔坐标转换到球面坐标，我们将使用 GeometricUtilities::Coordinates 命名空间的一个辅助函数。这个转换的前两个坐标对应于x-y面的极坐标。\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// 在本教程中，我们将使用一个简化的参数集。这里也可以使用ParameterHandler类，但为了使本教程简短，我们决定使用简单的结构。所有这些参数的实际意图将在接下来的类中描述，在它们各自使用的位置。\n\n// 下面的参数集控制着多网格机制的粗网格求解器、平滑器和网格间传输方案。我们用默认参数来填充它。\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// 这是该问题类的一般参数结构。你会发现这个结构分为几个类别，包括一般的运行时参数、级别限制、细化和粗化分数，以及单元加权的参数。它还包含一个上述结构的实例，用于多网格参数，这些参数将被传递给多网格算法。\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// 这是一个无矩阵的拉普拉斯算子的实现，基本上将接管其他教程中的`assemble_system()`函数的部分。所有成员函数的含义将在后面的定义中解释。\n\n// 我们将使用FEEvaluation类来评估正交点的解向量并进行积分。与其他教程不同的是，模板参数`度数`被设置为  $-1$  ，`一维正交数`被设置为  $0$  。在这种情况下，FEEvaluation会动态地选择正确的多项式度数和正交点的数量。在这里，我们为FEEvaluation引入一个带有正确模板参数的别名，这样我们以后就不用担心这些参数了。\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// 为了用AMG预处理程序解决最粗层次的方程系统，我们需要一个最粗层次的实际系统矩阵。为此，我们提供了一种机制，可以选择从无矩阵公式中计算出一个矩阵，为此我们引入了一个专门的SparseMatrix对象。在默认情况下，这个矩阵保持为空。一旦`get_system_matrix()`被调用，这个矩阵就会被填充（懒惰分配）。由于这是一个 \"const \"函数，我们需要在这里使用 \"mutable \"关键字。我们还需要一个约束对象来构建矩阵。\n\n    AffineConstraints<number>              constraints; \n    mutable TrilinosWrappers::SparseMatrix system_matrix; \n  }; \n\n// 下面的部分包含了初始化和重新初始化该类的函数。特别是，这些函数初始化了内部的MatrixFree实例。为了简单起见，我们还计算了系统右侧的向量。\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// 清除内部数据结构（在操作者被重复使用的情况下）。\n\n    this->system_matrix.clear(); \n\n// 复制约束条件，因为以后在计算系统矩阵时可能需要它们。\n\n    this->constraints.copy_from(constraints); \n\n// 设置MatrixFree。在正交点，我们只需要评估解的梯度，并用形状函数的梯度进行测试，所以我们只需要设置标志`update_gradients`。\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// 计算右手边的向量。为此，我们设置了第二个MatrixFree实例，它使用一个修改过的AffineConstraints，不包含由于Dirichlet-边界条件的约束。这个修改过的算子被应用于一个只设置了迪里希特值的向量。其结果是负的右手边向量。\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// 以下函数是多网格算法隐含需要的，包括平滑器。\n\n// 由于我们没有矩阵，所以要向DoFHandler查询自由度的数量。\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// 访问矩阵中的一个特定元素。这个函数既不需要也没有实现，但是，在编译程序时需要它。\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// 初始化给定的向量。我们只是把这个任务委托给同名的MatrixFree函数。\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// 在MatrixFree的帮助下，通过在所有单元中循环进行运算评估，并评估单元积分的效果（参见。`do_cell_integral_local()`和`do_cell_integral_global()`）。)\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// 执行转置的运算符评估。由于我们考虑的是对称的 \"矩阵\"，这个函数可以简单地将其任务委托给vmult()。\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// 由于我们没有一个系统矩阵，我们不能循环计算矩阵的对角线项。相反，我们通过对单位基向量进行一连串的运算符评估来计算对角线。为此，我们使用了MatrixFreeTools命名空间中的一个优化函数。之后再手动进行反转。\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// 在无矩阵的情况下，在这个类的初始化过程中没有设置系统矩阵。因此，如果需要的话，它必须在这里被计算出来。由于矩阵在本教程中只对线性元素进行计算（在粗略的网格上），这一点是可以接受的。矩阵的条目是通过运算符的评估序列得到的。为此，使用了优化函数 MatrixFreeTools::compute_matrix() 。矩阵只有在尚未设置的情况下才会被计算（懒惰分配）。\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// 对一个单元格批处理进行单元格积分，不需要收集和分散数值。MatrixFreeTools函数需要这个函数，因为这些函数直接对FEEvaluation的缓冲区进行操作。\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// 与上述相同，但可以访问全局向量。\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// 这个函数在一个单元格批次范围内的所有单元格批次上循环，并调用上述函数。\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// 这个函数用一连串提供的多网格对象来解决方程组。它的目的是为了尽可能的通用，因此有许多模板参数。\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// 我们在这里初始化电平运算符和切比雪夫平滑器。\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// 接下来，我们初始化粗略网格求解器。我们使用共轭梯度法和AMG作为预处理程序。\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// 最后，我们创建Multigrid对象，将其转换为预处理程序，并在共轭梯度求解器中使用它来解决线性方程组。\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// 上述函数处理给定的多网格对象序列的实际解决方案。这个函数创建了实际的多重网格层次，特别是运算符，以及作为MGTransferGlobalCoarsening对象的转移运算符。\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// 为每个多网格层次创建一个DoFHandler和操作符，以及，创建转移操作符。为了能够设置运算符，我们需要一组DoFHandler，通过p或h的全局粗化来创建。\n\n// 如果没有要求h-transfer，我们为`emplace_back()`函数提供一个空的删除器，因为我们的DoFHandler的Triangulation是一个外部字段，其析构器在其他地方被调用。\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// 确定多栅格操作的总层数，并为所有层数分配足够的内存。\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// 从最小（最粗）到最大（最细）级别的循环，并相应地设置DoFHandler。我们从h层开始，在这里我们分布在越来越细的网格上的线性元素。\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// 在我们达到最细的网格后，我们将调整每一层的多项式度数。我们反向迭代我们的数据结构，从包含所有活动FE指数信息的最细网格开始。然后我们逐级降低每个单元的多项式度数。\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// 接下来，我们将在每个多重网格层面上创建所有额外需要的数据结构。这涉及到确定具有同质Dirichlet边界条件的约束，并像在活动层上一样建立运算器。\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//根据多网格求解器类的需要，在单个算子中设置网格间算子和收集转移算子。\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// 最后，继续用多网格法解决问题。\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// 现在，我们将最后声明这个程序的主类，它在随后的精炼函数空间上求解拉普拉斯方程。它的结构看起来很熟悉，因为它与  step-27  和  step-40  的主类类似。基本上只增加了两个。\n\n// - 持有系统矩阵的SparseMatrix对象已经被MatrixFree公式中的LaplaceOperator类对象所取代。\n\n// - 加入了一个 parallel::CellWeights, 的对象，它将帮助我们实现负载平衡。\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// 构造函数以一个初始化器列表开始，该列表看起来与  step-40  的列表相似。我们再次准备好ConditionalOStream对象，只允许第一个进程在控制台输出任何东西，并正确初始化计算计时器。\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// 我们需要在构造函数的实际主体中为hp-functionality准备数据结构，并在参数结构的指定范围内为每个度数创建相应的对象。由于我们只处理非扭曲的矩形单元，在这种情况下，一个线性映射对象就足够了。\n\n// 在参数结构中，我们为函数空间以合理的分辨率运行的层级提供范围。多网格算法需要在最粗的层次上使用线性元素。所以我们从最低的多项式度数开始，用连续的高度数填充集合，直到达到用户指定的最大值。\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// 由于我们的FECollection包含的有限元比我们想用于求解的有限元近似值要多，我们想限制活动FE指数可以操作的范围。为此，FECollection类允许注册一个层次结构，在p-精简和p-粗化的情况下，分别决定后续的和前面的有限元。 hp::Refinement 命名空间中的所有函数都会参考这个层次结构来确定未来的FE指数。我们将注册这样一个层次结构，它只对建议范围内的多项式程度的有限元起作用  <code>[min_p_degree, max_p_degree]</code>  。\n\n    const unsigned int min_fe_index = prm.min_p_degree - 1; \n    fe_collection.set_hierarchy( \n\n   /*下一个_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    /*上一页_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// 我们以默认配置初始化 FESeries::Legendre 对象，以便进行平滑度估计。\n\n    legendre = std::make_unique<FESeries::Legendre<dim>>( \n      SmoothnessEstimator::Legendre::default_fe_series(fe_collection)); \n\n// 接下来的部分会很棘手。在执行细化的过程中，有几个hp-算法需要干扰三角形对象上的实际细化过程。我们通过将几个函数连接到 Triangulation::Signals: 信号，在实际细化过程中的不同阶段被调用，并触发所有连接的函数来做到这一点。我们需要这个功能来实现负载平衡和限制相邻单元的多项式度数。\n\n// 对于前者，我们希望给每个单元分配一个权重，这个权重与它未来的有限元的自由度数成正比。该库提供了一个类 parallel::CellWeights ，允许在细化过程中的正确位置轻松地附加单个权重，即在所有细化和粗化标志被正确设置为hp-adaptation之后，以及在即将发生的负载平衡的重新划分之前。可以注册一些函数，这些函数将以  $a (n_\\text{dofs})^b$  提供的一对参数的形式附加权重  $(a,b)$  。我们在下文中注册了这样一个函数。每个单元在创建时将被赋予一个恒定的权重，这个值是1000（见  Triangulation::Signals::cell_weight).  ）。\n\n// 为了实现负载平衡，像我们使用的高效求解器应该与拥有的自由度数量成线性比例。此外，为了增加我们想要附加的权重的影响，确保单个权重将超过这个基础权重的数量级。我们相应地设置单元加权的参数。大的加权系数为 $10^6$ ，指数为 $1$  。\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// 在h-adaptive应用中，我们通过限制相邻单元的细化水平的差异为1来确保2:1的网格平衡。通过下面代码片段中的第二个调用，我们将确保相邻单元的p级数也是如此：未来有限元的级数不允许相差超过指定的差值。函数 hp::Refinement::limit_p_level_difference 可以处理这个问题，但需要与并行环境中的一个非常特殊的信号相连。问题是，我们需要知道网格的实际细化情况，以便相应地设置未来的FE指数。由于我们要求p4est神谕进行细化，我们需要确保Triangulation已经先用神谕的适应标志进行了更新。 parallel::distributed::TemporarilyMatchRefineFlags 的实例化在其生命期内正是如此。因此，我们将在限制p级差之前创建这个类的对象，并将相应的lambda函数连接到信号 Triangulation::Signals::post_p4est_refinement, 上，该信号将在神谕被完善之后，但在三角法被完善之前被触发。此外，我们指定这个函数将被连接到信号的前面，以确保修改在连接到同一信号的任何其他函数之前进行。\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                                                 /*包含=  */ min_fe_index);\n      }, \n      boost::signals2::at_front); \n  } \n\n//  @sect4{LaplaceProblem::initialize_grid}  \n\n// 对于L型域，我们可以使用 GridGenerator::hyper_L() 这个函数，如 step-50 中所演示的。然而在二维的情况下，该函数只去除第一象限，而在我们的方案中我们需要去除第四象限。因此，我们将使用一个不同的函数 GridGenerator::subdivided_hyper_L() ，它给我们更多的选择来创建网格。此外，我们在制定该函数时，也会生成一个三维网格：二维L型域基本上会在正Z方向上拉长1。\n\n// 我们首先假装建立一个  GridGenerator::subdivided_hyper_rectangle().  我们需要提供的参数是左下角和右上角的点对象，以及基本网格在每个方向的重复次数。我们为前两个维度提供这些参数，对更高的第三维度单独处理。\n\n// 为了创建一个L型域，我们需要去除多余的单元。为此，我们相应地指定 <code>cells_to_remove</code> 。我们希望从负方向的每一个单元格中移除一个单元格，但从正的x方向移除一个。\n\n// 最后，我们提供与所提供的最小网格细化水平相对应的初始细化数。此外，我们相应地设置初始活动FE指数。\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// 这个函数看起来和 step-40 的函数完全一样，但是你会注意到没有系统矩阵以及围绕它的脚手架。相反，我们将在这里初始化 <code>laplace_operator</code> 中的MatrixFree公式。对于边界条件，我们将使用本教程前面介绍的Solution类。\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// 这是一个打印关于方程组及其划分的额外诊断的函数。除了通常的全局活动单元数和自由度外，我们还输出它们的局部等价物。为了规范输出，我们将用 Utilities::MPI::gather 操作将局部数量传达给第一个进程，然后由该进程输出所有信息。本地量的输出只限于前8个进程，以避免终端的杂乱。\n\n// 此外，我们想打印数值离散化中的多项式度数的频率。由于这些信息只存储在本地，我们将计算本地拥有的单元上的有限元，随后通过 Utilities::MPI::sum. 进行交流。\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// 围绕解决方案的脚手架与  step-40  的类似。我们准备一个符合MatrixFree要求的向量，并收集本地相关的自由度，我们解决了方程系统。解决方法是通过前面介绍的函数进行的。\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// 这个函数只包含其他教程中典型的 <code>refine_grid</code> 函数的一部分，在这个意义上是新的。在这里，我们将只计算与实际细化网格相适应的所有指标。我们这样做的目的是将所有的指标写到文件系统中，以便为以后储存。\n\n// 由于我们处理的是一个椭圆问题，我们将再次利用KellyErrorEstimator，但有一点不同。修改底层面积分的缩放系数，使其取决于相邻元素的实际多项式程度，这对hp-adaptive应用是有利的  @cite davydov2017hp  。我们可以通过指定你所注意到的附加参数中的最后一个参数来做到这一点。其他的实际上只是默认的。\n\n// 为了hp-adaptation的目的，我们将用教程介绍中的策略来计算平滑度估计，并使用 SmoothnessEstimator::Legendre. 中的实现 在参数结构中，我们将最小多项式度数设置为2，因为似乎平滑度估计算法在处理线性元素时有问题。\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      /*策略=  */ \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// 有了之前计算出的指标，我们最终将标记所有单元进行适应，同时在这个函数中执行细化。和以前的教程一样，我们将使用 \"固定数字 \"策略，但现在是针对hp-adaptation。\n\n  template <int dim> \n  void LaplaceProblem<dim>::adapt_resolution() \n  { \n    TimerOutput::Scope t(computing_timer, \"adapt resolution\"); \n\n// 首先，我们将根据每个单元的误差估计值来设置细化和粗化标志。这里没有什么新东西。\n\n// 我们将使用在其他deal.II教程中阐述过的一般细化和粗化比例：使用固定数字策略，我们将标记所有单元中的30%进行细化，3%进行粗化，如参数结构中提供的。\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// 接下来，我们将对hp-adaptation进行所有调整。我们想细化和粗化那些在上一步中被标记的单元，但需要决定是通过调整网格分辨率还是调整多项式程度来实现。\n\n// 下一个函数调用根据之前计算的平滑度指标设置未来的FE指数，作为p-adaptation指标。这些指数将只设置在那些分配了细化或粗化标志的单元上。\n\n// 对于p-adaptation分数，我们将采取一个有根据的猜测。由于我们只期望在我们的方案中出现一个单一的奇点，即在域的原点，而在其他任何地方都有一个平滑的解决方案，所以我们希望强烈倾向于使用p-adaptation而不是h-adaptation。这反映在我们对p-精简和p-粗化都选择了90%的分数。\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// 在这个阶段，我们既有未来的FE指数，也有经典的细化和粗化标志，后者将由 Triangulation::execute_coarsening_and_refinement() 解释为h-适应性。我们希望只对细胞施加一种适应，这就是下一个函数将为我们解决的问题。简而言之，在分配有两种类型指标的单元格上，我们将倾向于p-适应的那一种，并删除h-适应的那一种。\n\n    hp::Refinement::choose_p_over_h(dof_handler); \n\n// 设置完所有指标后，我们将删除那些超过参数结构中提供的水平范围的指定限制的指标。由于提供的有限元数量有限，这种限制自然会出现在p-adaptation中。此外，我们在构造函数中为p-adaptation注册了一个自定义层次结构。现在，我们需要像  step-31  中那样，在h-adaptive的上下文中手动完成。\n\n// 我们将遍历指定的最小和最大层次上的所有单元格，并删除相应的标志。作为一种选择，我们也可以通过相应地设置未来的FE指数来标记这些单元的p适应性，而不是简单地清除细化和粗化的标志。\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// 最后，我们就剩下执行粗化和细化了。在这里，不仅网格会被更新，而且所有以前的未来FE指数也会变得活跃。\n\n// 记得我们在构造函数中为三角化信号附加了函数，将在这个函数调用中被触发。所以会有更多的事情发生：加权重新分区将被执行以确保负载平衡，以及我们将限制相邻单元之间的p级差。\n\n    triangulation.execute_coarsening_and_refinement(); \n  } \n\n//  @sect4{LaplaceProblem::output_results}  \n\n// 在并行应用中向文件系统写入结果的工作方式与  step-40  中完全相同。除了我们在整个教程中准备的数据容器外，我们还想写出网格上每个有限元的多项式程度，以及每个单元所属的子域。我们在这个函数的范围内为此准备必要的容器。\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// 实际的运行函数看起来又和  step-40  非常相似。唯一增加的是实际循环之前的括号内的部分。在这里，我们将预先计算Legendre变换矩阵。一般来说，每当需要某个矩阵时，这些矩阵将通过懒惰分配的方式进行实时计算。然而，出于计时的目的，我们希望在实际的时间测量开始之前，一次性地计算它们。因此，我们将把它们的计算指定为自己的范围。\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// 最后一个函数是 <code>main</code> 函数，它将最终创建并运行一个LaplaceOperator实例。它的结构与其他大多数教程程序相似。\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": "// 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": "/* \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": "\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": "/*!\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": "/* 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": "#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": "/**\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": "#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 <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": "// 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": "//=======================================================================\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": "/******************************************************************************\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": "/* 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) << \" µs, 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) << \" µs, 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": "// 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": "/* 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#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\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": "#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": "#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": "/**\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": "/*  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": "//\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 \"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 <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// 像素坐标转相机归一化坐标\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    //-- 读取图像\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<<\"一共找到了\"<<matches.size() <<\"组匹配点\"<<endl;\n\n    // 建立3D点\n    Mat d1 = imread ( argv[3], CV_LOAD_IMAGE_UNCHANGED );       // 深度图为16位无符号数，单通道图像\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 ); // 调用OpenCV 的 PnP 求解，可选择EPNP，DLS等方法\n    Mat R;\n    cv::Rodrigues ( r, R ); // r为旋转向量形式，用Rodrigues公式转换为矩阵\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    //-- 初始化\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    //-- 第一步:检测 Oriented FAST 角点位置\n    detector->detect ( img_1,keypoints_1 );\n    detector->detect ( img_2,keypoints_2 );\n\n    //-- 第二步:根据角点位置计算 BRIEF 描述子\n    descriptor->compute ( img_1, keypoints_1, descriptors_1 );\n    descriptor->compute ( img_2, keypoints_2, descriptors_2 );\n\n    //-- 第三步:对两幅图像中的BRIEF描述子进行匹配，使用 Hamming 距离\n    vector<DMatch> match;\n    // BFMatcher matcher ( NORM_HAMMING );\n    matcher->match ( descriptors_1, descriptors_2, match );\n\n    //-- 第四步:匹配点对筛选\n    double min_dist=10000, max_dist=0;\n\n    //找出所有匹配之间的最小距离和最大距离, 即是最相似的和最不相似的两组点之间的距离\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    //当描述子之间的距离大于两倍的最小距离时,即认为匹配有误.但有时候最小距离会非常小,设置一个经验值30作为下限.\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() // 重置\n    {\n        _estimate = Sophus::SE3d();\n    }\n    \n    virtual void oplusImpl( const double* update ) // 更新\n    {\n        Eigen::Map<const Vector6d> update_vec(update);\n        setEstimate(Sophus::SE3d::exp(update_vec) * _estimate);\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\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// 初始化g2o\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose 维度为 6, landmark 维度为 3\n    std::unique_ptr<Block::LinearSolverType> linearSolver = g2o::make_unique<g2o::LinearSolverCSparse<Block::PoseMatrixType>>(); // 线性方程求解器\n    std::unique_ptr<Block> solver_ptr = g2o::make_unique<Block> ( move(linearSolver) );     // 矩阵块求解器\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 中必须设置 marg 参见第十讲内容\n        optimizer.addVertex ( point );\n    }\n\n    // parameter: camera intrinsics\n    g2o::CameraParameters* camera = new g2o::CameraParameters (\n        K.at<double> ( 0,0 ), Eigen::Vector2d ( K.at<double> ( 0,2 ), K.at<double> ( 1,2 ) ), 0\n    );\n    camera->setId ( 0 );\n    optimizer.addParameter ( camera );\n\n    // edges\n    index = 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    // 初始化g2o\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose 维度为 6, landmark 维度为 3\n    std::unique_ptr<Block::LinearSolverType> linearSolver = g2o::make_unique<g2o::LinearSolverCSparse<Block::PoseMatrixType>>(); // 线性方程求解器\n    std::unique_ptr<Block> solver_ptr = g2o::make_unique<Block> ( move(linearSolver) );     // 矩阵块求解器\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 中必须设置 marg 参见第十讲内容\n        optimizer.addVertex ( point );\n    }\n\n    // parameter: camera intrinsics\n    g2o::CameraParameters* camera = new g2o::CameraParameters (\n        K.at<double> ( 0,0 ), Eigen::Vector2d ( K.at<double> ( 0,2 ), K.at<double> ( 1,2 ) ), 0\n    );\n    camera->setId ( 0 );\n    optimizer.addParameter ( camera );\n\n    // edges\n    index = 1;\n    for ( const 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": "//=======================================================================\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": "#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": "#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": "//   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": "#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": "#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": "/* 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": "/*\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": "#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 <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": "#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": "/**\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": "/*\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": "//  (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": "#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": "#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": "/*\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": "/// 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": "//  (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": "//  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": "//  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": "/**\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": "/*\n * SPDX-FileCopyrightText: © 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°, -180°].\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": "#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": "/*!\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": "//=======================================================================\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": "///////////////////////////////////////////////////////////////////////////////\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 <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<stdio.h>\n#include\"mex.h\"\n\n#include \"EdgeSE3ProjectDirectWithDirstortG2oLM.cpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n \n// 李群李代数 库 \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// 一次测量的值，包括一个世界坐标系下三维点,以及投影的对应的图像\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    // 初始化g2o\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6,1>> DirectBlock;  // 求解的向量是6＊1的\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    // 添加顶点\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    // 添加边\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 <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": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// 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": "// 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": "/* 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": "//  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 *  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": "/***********************************************************************\nThis file is part of the librjmcmc project source files.\n\nCopyright : Institut Geographique National (2008-2012)\nContributors : Mathieu Brédif, Olivier Tournaire, Didier Boldo\nemail : librjmcmc@ign.fr\n\nThis software is a generic C++ library for stochastic optimization.\n\nThis software is governed by the CeCILL license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the software under the terms of the CeCILL\nlicense as circulated by CEA, CNRS and INRIA at the following URL\n\"http://www.cecill.info\".\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided only\nwith a limited warranty and the software's author, the holder of the\neconomic rights, and the successive licensors have only limited liability.\n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading, using, modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean that it is complicated to manipulate, and that also\ntherefore means that it is reserved for developers and experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test the software's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or\ndata to be ensured and, more generally, to use and operate it in the\nsame conditions as regards security.\n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL license and that you accept its terms.\n\n***********************************************************************/\n\n#ifndef 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 * 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": "#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": "/*\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// 这个例子程序是对 step-22 的轻微修改，使用Trilinos并行运行，以演示交易.II中周期性边界条件的使用。因此我们不讨论大部分的源代码，只对处理周期性约束的部分进行评论。其余的请看 step-22 和底部的完整源代码。\n\n// 为了实现周期性边界条件，只有两个函数需要修改。\n\n// -  <code>StokesProblem<dim>::setup_dofs()</code>  : 用周期性约束来填充AffineConstraints对象\n\n// -  <code>StokesProblem<dim>::create_mesh()</code>  : 为分布式三角形提供周期性信息。\n\n// 程序的其余部分与 step-22 相同，所以让我们跳过这一部分，只在下面显示这两个函数。完整的程序可以在下面的 \"普通程序 \"部分找到）。\n\n//  @cond  跳过\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// 在我们可以规定周期性约束之前，我们需要确保位于域的对面但由周期性面连接的单元是幽灵层的一部分，如果其中一个单元存储在本地处理器上。在这一点上，我们需要考虑我们要如何规定周期性。左边边界上的面的顶点 $\\text{vertices}_2$ 应该与下面边界上的面的顶点 $\\text{vertices}_1$ 相匹配，由 $\\text{vertices}_2=R\\cdot \\text{vertices}_1+b$ 给出，其中旋转矩阵 $R$ 和偏移量 $b$ 由\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//  给出。 我们将所得信息保存到这里的数据结构是基于三角结构的。\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// 现在，只要调用 parallel::distributed::Triangulation::add_periodicity. 就可以告诉三角函数所需的周期性，特别容易。\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// 在我们为网格提供了周期性约束的必要信息后，我们现在可以实际创建它们。对于描述匹配，我们使用与之前相同的方法，也就是说，左边边界上的一个面的 $\\text{vertices}_2$ 应该与下面边界上的一个面的顶点 $\\text{vertices}_1$ 匹配，由 $\\text{vertices}_2=R\\cdot \\text{vertices}_1+b$  ]，其中旋转矩阵 $R$ 和偏移量 $b$ 由\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//  给出。 这两个对象不仅描述了应该如何匹配面，而且还描述了解决方案应该从 $\\text{face}_2$ 转换到 $\\text{face}_1$ 的意义。\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// 为了设置约束，我们首先将周期性信息存储在一个类型为 <code>std::vector@<GridTools::PeriodicFacePair<typename 的辅助对象中。\n// DoFHandler@<dim@>::%cell_iterator@>  </code>。周期性边界的边界指标为2（x=0）和3（y=0）。所有其他的参数我们之前已经设置好了。在这种情况下，方向并不重要。由于 $\\text{vertices}_2=R\\cdot \\text{vertices}_1+b$ 这正是我们想要的。\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// 接下来，我们需要提供关于解决方案中哪些矢量值分量应该被旋转的信息。由于我们在这里选择只约束速度，并且从解决方案矢量的第一个分量开始，我们只需插入一个0。\n\n      std::vector<unsigned int> first_vector_components; \n      first_vector_components.push_back(0); \n\n// 在设置了周期性_vector中的所有信息之后，我们要做的就是告诉make_periodicity_constraints来创建所需的约束。\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// 然后程序的其余部分又与  step-22  相同。我们现在省略它，但和以前一样，你可以在下面的 \"普通程序 \"部分找到这些部分。\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": "#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": "// 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 * 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 <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": "/*\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": "﻿//*****************************************************************************\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émi 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[Τᴴ¹], GetStand()->m_equations.m_EAS[Τᴴ²]);\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[Τᴴ]);\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 (± 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[ʎ0] - 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[ʎa], T);\r\n\r\n\t\t\tdouble DD = min(0.0, T - m_equations.m_EWD[ʎb]);//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[ʎ2], m_equations.m_EWD[ʎ3]);\r\n\t\tint begin = (int)Round((m_equations.m_EWD[ʎ0] - 1) + m_equations.m_EWD[ʎ1] * 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[ʎa], T);\r\n//\t\t\tdouble NDD = min(0.0, T - m_equations.m_EWD[ʎb]);//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[ʎ0] - 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[Τᴴ]);\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 = ∞ 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// 程序一开始就包括了一堆include文件，我们将在程序的各个部分使用这些文件。其中大部分在以前的教程中已经讨论过了。\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// 这里有一些我们需要的C++标准头文件。\n\n#include <cmath> \n#include <iostream> \n#include <fstream> \n#include <string> \n\n// 这个序言的最后部分是将dealii命名空间中的所有内容导入到这个程序中的所有内容中。\n\nnamespace Step34 \n{ \n  using namespace dealii; \n// @sect3{Single and double layer operator kernels}  \n\n// 首先，让我们定义一下边界积分方程的机制。\n\n// 以下两个函数是单层和双层势能核的实际计算，即  $G$  和  $\\nabla G$  。只有当矢量 $R = \\mathbf{y}-\\mathbf{x}$ 不同于零时，它们才是定义良好的。\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// 边界元素方法代码的结构与有限元素代码的结构非常相似，所以这个类的成员函数与其他大多数教程程序的成员函数一样。特别是，现在你应该熟悉从外部文件中读取参数，以及将不同的任务分割成不同的模块。这同样适用于边界元素方法，我们不会对其进行过多的评论，只是对其中的差异进行评论。\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// 我们在这里发现的唯一真正不同的函数是装配程序。我们以最通用的方式编写了这个函数，以便能够方便地推广到高阶方法和不同的基本解（例如斯托克斯或麦克斯韦）。\n\n// 最明显的区别是，最终的矩阵是完整的，而且我们在通常的单元格循环内有一个嵌套的循环，访问所有自由度的支持点。 此外，当支持点位于我们所访问的单元内时，我们所执行的积分就会变成单数。\n\n// 实际的结果是，我们有两套正交公式、有限元值和临时存储，一套用于标准积分，另一套用于奇异积分，在必要时使用。\n\n    void assemble_system(); \n\n// 对于这个问题的解决有两种选择。第一个是使用直接求解器，第二个是使用迭代求解器。我们选择了第二种方案。\n\n// 我们组装的矩阵不是对称的，我们选择使用GMRES方法；然而为边界元素方法构建一个有效的预处理程序并不是一个简单的问题。这里我们使用一个非预处理的GMRES求解器。迭代求解器的选项，如公差、最大迭代次数等，都是通过参数文件选择的。\n\n    void solve_system(); \n\n// 一旦我们得到了解决方案，我们将计算计算出的势的 $L^2$ 误差，以及实体角的近似值的 $L^\\infty$ 误差。我们使用的网格是平滑曲线的近似值，因此计算出的角的分量或实体角的对角线矩阵  $\\alpha(\\mathbf{x})$  应该一直等于  $\\frac 12$  。在这个例程中，我们输出势的误差和计算角度的近似值的误差。注意，后者的误差实际上不是计算角度的误差，而是衡量我们对球体和圆的近似程度。\n\n// 对角度的计算做一些实验，对于较简单的几何形状，可以得到非常准确的结果。为了验证这一点，你可以在read_domain()方法中注释掉tria.set_manifold(1, manifold)一行，并检查程序生成的alpha。通过删除这个调用，每当细化网格时，新的节点将沿着构成粗略网格的直线放置，而不是被拉到我们真正想要近似的表面。在三维案例中，球体的粗网格是从一个立方体开始得到的，得到的字母值正好是面的节点上的 $\\frac 12$ ，边的节点上的 $\\frac 34$ 和顶点的8个节点上的 $\\frac 78$ 。\n\n    void compute_errors(const unsigned int cycle); \n\n// 一旦我们在一维领域得到了一个解决方案，我们就想把它插值到空间的其他部分。这可以通过在compute_exterior_solution()函数中再次进行解与核的卷积来实现。\n\n// 我们想绘制速度变量，也就是势解的梯度。势解只在边界上是已知的，但我们使用与基本解的卷积在标准的二维连续有限元空间上进行插值。外推解的梯度图将给我们提供我们想要的速度。\n\n// 除了外域上的解，我们还在output_results()函数中输出域的边界上的解，当然了。\n\n    void compute_exterior_solution(); \n\n    void output_results(const unsigned int cycle); \n\n// 为了实现不受维度限制的编程，我们对这个单一的函数进行了专业化处理，以提取整合单元内部的奇异核所需的奇异正交公式。\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// 通常的deal.II类可以通过指定问题的 \"二维 \"来用于边界元素方法。这是通过将Triangulation, FiniteElement和DoFHandler的可选第二模板参数设置为嵌入空间的维度来实现的。在我们的例子中，我们生成了嵌入在二维或三维空间的一维或二维网格。\n\n// 可选参数默认等于第一个参数，并产生我们在之前所有例子中看到的通常的有限元类。\n\n// 该类的构造方式是允许任意的域（通过高阶映射）和有限元空间的逼近顺序。有限元空间和映射的顺序可以在该类的构造函数中选择。\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// 在BEM方法中，生成的矩阵是密集的。根据问题的大小，最终的系统可能通过直接的LU分解来解决，或者通过迭代方法来解决。在这个例子中，我们使用了一个无条件的GMRES方法。为BEM方法建立一个预处理程序是不容易的，我们在此不做处理。\n\n    FullMatrix<double> system_matrix; \n    Vector<double>     system_rhs; \n\n// 接下来的两个变量将表示解决方案 $\\phi$ 以及一个向量，它将保存 $\\alpha(\\mathbf x)$ 的值（从一个点 $\\mathbf x$ 可见的 $\\Omega$ 的部分）在我们形状函数的支持点。\n\n    Vector<double> phi; \n    Vector<double> alpha; \n\n// 收敛表是用来输出精确解和计算出的字母的误差的。\n\n    ConvergenceTable convergence_table; \n\n// 下面的变量是我们通过参数文件来填充的。 本例中我们使用的新对象是 Functions::ParsedFunction 对象和QuadratureSelector对象。\n\n//  Functions::ParsedFunction 类允许我们通过参数文件方便快捷地定义新的函数对象，自定义的定义可以非常复杂（关于所有可用的选项，见该类的文档）。\n\n// 我们将使用QuadratureSelector类来分配正交对象，该类允许我们根据一个识别字符串和公式本身的可能程度来生成正交公式。我们用它来允许自定义选择标准积分的正交公式，并定义奇异正交规则的顺序。\n\n// 我们还定义了几个参数，这些参数是在我们想把解决方案扩展到整个领域的情况下使用的。\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//构造函数初始化各种对象的方式与有限元程序（如  step-4  或  step-6  ）中的方式基本相同。这里唯一的新成分是ParsedFunction对象，它在构造时需要说明组件的数量。\n\n// 对于精确解来说，向量分量的数量是1，而且不需要任何操作，因为1是ParsedFunction对象的默认值。然而，风需要指定dim组件。注意，在为 Functions::ParsedFunction, 的表达式声明参数文件中的条目时，我们需要明确指定分量的数量，因为函数 Functions::ParsedFunction::declare_parameters 是静态的，对分量的数量没有了解。\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// 对于二维和三维，我们将默认的输入数据设置为：解为  $x+y$  或  $x+y+z$  。实际计算出的解在无穷大时的数值为零。在这种情况下，这与精确解相吻合，不需要额外的修正，但是你应该注意，我们任意设置了 $\\phi_\\infty$ ，而我们传递给程序的精确解需要在无穷远处有相同的值，才能正确计算出误差。\n\n//  Functions::ParsedFunction 对象的使用是非常直接的。 Functions::ParsedFunction::declare_parameters 函数需要一个额外的整数参数，指定给定函数的分量数量。它的默认值是1。当相应的 Functions::ParsedFunction::parse_parameters 方法被调用时，调用对象必须有与这里定义的相同数量的组件，否则会产生异常。\n\n// 在声明条目时，我们同时声明了二维和三维的函数。然而只有二维的最终被解析。这使得我们对二维和三维问题都只需要一个参数文件。\n\n// 注意，从数学的角度来看，边界上的风函数应该满足条件 $\\int_{\\partial\\Omega} \\mathbf{v}\\cdot \\mathbf{n} d \\Gamma = 0$  ，这样问题才会有解。如果不满足这个条件，那么就找不到解，求解器也就不会收敛。\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// 在求解器部分，我们设置所有的SolverControl参数。然后，该对象将在solve_system()函数中被送入GMRES求解器。\n\n    prm.enter_subsection(\"Solver\"); \n    SolverControl::declare_parameters(prm); \n    prm.leave_subsection(); \n\n// 在向ParameterHandler对象声明了所有这些参数后，让我们读取一个输入文件，该文件将为这些参数提供其值。然后我们继续从ParameterHandler对象中提取这些值。\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// 最后，这里是另一个如何在独立维度编程中使用参数文件的例子。 如果我们想关闭两个模拟中的一个，我们可以通过设置相应的 \"运行2D模拟 \"或 \"运行3D模拟 \"标志为假来实现。\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// 边界元素法三角剖分与（dim-1）维三角剖分基本相同，不同之处在于顶点属于（dim）维空间。\n\n// deal.II中支持的一些网格格式默认使用三维点来描述网格。这些格式与deal.II的边界元素方法功能兼容。特别是我们可以使用UCD或GMSH格式。在这两种情况下，我们必须特别注意网格的方向，因为与标准有限元的情况不同，这里没有进行重新排序或兼容性检查。 所有的网格都被认为是有方向性的，因为它们被嵌入到一个高维空间中。参见GridIn和Triangulation的文档，以进一步了解三角结构中单元的方向。在我们的例子中，网格的法线是外在于2D的圆或3D的球体。\n\n// 对边界元素网格进行适当细化所需要的另一个细节是对网格所逼近的流形的准确描述。对于标准有限元网格的边界，我们已经多次看到了这一点（例如在 step-5 和 step-6 中），这里的原理和用法是一样的，只是SphericalManifold类需要一个额外的模板参数来指定嵌入空间维度。\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// 对  Triangulation::set_manifold  的调用复制了流形（通过  Manifold::clone()),  所以我们不需要担心对  <code>manifold</code>  的无效指针。\n\n    tria.set_manifold(1, manifold); \n  } \n// @sect4{BEMProblem::refine_and_resize}  \n\n// 这个函数对网格进行全局细化，分配自由度，并调整矩阵和向量的大小。\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// 下面是这个程序的主要功能，组装与边界积分方程相对应的矩阵。\n\n  template <int dim> \n  void BEMProblem<dim>::assemble_system() \n  { \n\n// 首先我们用正交公式初始化一个FEValues对象，用于在非奇异单元中进行内核积分。这个正交公式是通过参数文件选择的，并且需要相当精确，因为我们要积分的函数不是多项式函数。\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// 与有限元方法不同的是，如果我们使用拼合边界元方法，那么在每个装配循环中，我们只装配与一个自由度（与支撑点 $i$ 相关的自由度）和当前单元之间的耦合信息。这是用fe.dofs_per_cell元素的向量完成的，然后将其分配到全局行的矩阵中  $i$  。以下对象将持有这些信息。\n\n    Vector<double> local_matrix_row_i(fe.n_dofs_per_cell()); \n\n// 索引  $i$  运行在拼合点上，这是  $i$  第三个基函数的支持点，而  $j$  运行在内部积分点上。\n\n// 我们构建一个支持点的向量，它将用于局部积分。\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// 这样做之后，我们就可以开始对所有单元进行积分循环，首先初始化FEValues对象，得到正交点的 $\\mathbf{\\tilde v}$ 的值（这个向量场应该是常数，但更通用也无妨）。\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// 然后我们在当前单元上形成所有自由度的积分（注意，这包括不在当前单元上的自由度，这与通常的有限元积分有偏差）。如果其中一个局部自由度与支持点 $i$ 相同，我们需要执行的积分是单数。因此，在循环的开始，我们检查是否是这种情况，并存储哪一个是奇异指数。\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// 然后我们进行积分。如果指数 $i$ 不是局部自由度之一，我们只需将单层项加到右边，将双层项加到矩阵中。\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// 现在我们处理更微妙的情况。如果我们在这里，这意味着在 $j$ 索引上运行的单元包含support_point[i]。在这种情况下，单层和双层势都是单数，它们需要特殊处理。            \n//每当在给定单元内进行积分时，就会使用一个特殊的正交公式，允许人们对参考单元上的奇异权重进行任意函数的积分。            \n//正确的正交公式由get_singular_quadrature函数选择，下面将详细说明。\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// 最后，我们需要将当前单元格的贡献添加到全局矩阵中。\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// 积分运算符的第二部分是术语  $\\alpha(\\mathbf{x}_i) \\phi_j(\\mathbf{x}_i)$  。由于我们使用的是配位方案， $\\phi_j(\\mathbf{x}_i)=\\delta_{ij}$  而相应的矩阵是一个对角线的矩阵，其条目等于 $\\alpha(\\mathbf{x}_i)$  。\n\n// 计算这个实体角的对角矩阵的一个快速方法是使用诺伊曼矩阵本身。只需将该矩阵与一个元素都等于-1的向量相乘，就可以得到阿尔法角或实体角的对角线矩阵（见介绍中的公式）。然后将这个结果加回到系统矩阵对象上，得到矩阵的最终形式。\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// 下一个函数简单地解决了线性系统。\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// 误差的计算在其他所有的例子程序中都是完全一样的，我们就不做过多的评论。请注意，在有限元方法中使用的方法在这里也可以使用。\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//可以直接使用 Vector::linfty_norm() 函数来计算α向量的误差，因为在每个节点上，该值应该是 $\\frac 12$  。然后，所有的误差都会被输出并附加到我们的ConvergenceTable对象中，以便以后计算收敛率。\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// 奇异积分需要仔细选择正交规则。特别是deal.II库提供了为对数奇异性（QGaussLog, QGaussLogR）以及1/R奇异性（QGaussOneOverR）量身定制的正交规则。\n\n// 奇异积分通常是通过构建具有奇异权重的加权正交公式得到的，因此可以写成\n\n// \\f[ \\int_K f(x) s(x) dx = \\sum_{i=1}^N w_i f(q_i) \\f]\n\n// 其中 $s(x)$ 是一个给定的奇点，权重和正交点 $w_i,q_i$ 是精心选择的，以使上述公式对某类函数 $f(x)$ 是一个等式。\n\n// 在我们目前看到的所有有限元例子中，正交点本身的权重（即函数  $s(x)$  ），总是不断地等于1。 对于奇异积分，我们有两个选择：我们可以使用上面的定义，从积分中剔除奇异性（即用特殊的正交规则对 $f(x)$ 进行积分），或者我们可以要求正交规则用 $s(q_i)$ 对权重 $w_i$ 进行 \"标准化\"。\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// 我们通过QGaussLogR和QGaussOneOverR的 @p factor_out_singularity 参数来使用这第二种选择。\n\n// 这些积分有些微妙，特别是在二维空间，由于从实数到参考单元的转换，积分的变量是以转换的行列式为尺度的。\n\n// 在二维空间中，这个过程不仅会导致一个因子作为常数出现在整个积分上，而且还会导致一个需要评估的额外积分。\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// 这个过程由QGaussLogR类的构造函数来处理，它增加了额外的正交点和权重，以考虑到积分的第二部分。\n\n// 类似的推理应该在三维情况下进行，因为奇异正交是在参考单元的半径 $r$ 的逆上定制的，而我们的奇异函数生活在实空间，然而在三维情况下一切都更简单，因为奇异性与变换的行列式成线性比例。这使我们可以只建立一次奇异的二维正交规则，并在所有单元格中重复使用。\n\n// 在一维的奇异积分中，这是不可能的，因为我们需要知道正交的缩放参数，而这个参数并不是先验的。这里，正交规则本身也取决于当前单元格的大小。出于这个原因，有必要为每个单数积分创建一个新的正交。\n\n// 不同的正交规则是在get_singular_quadrature中建立的，它专门用于dim=2和dim=3，它们在assemble_system函数中被检索。作为参数给出的索引是奇异点所在的单位支持点的索引。\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// 我们还想知道一些关于外域中电势 $\\phi$ 的值：毕竟我们考虑边界积分问题的动机是想知道外域中的速度!\n\n// 为此，我们在此假设边界元素域包含在盒子 $[-2,2]^{\\text{dim}}$ 中，我们用与基本解的卷积来推算这个盒子内的实际解。这方面的公式在介绍中已经给出。\n\n// 整个空间的解的重建是在一个连续的、尺寸为dim的有限元网格上完成的。这些都是常用的，我们不做进一步评论。在函数的最后，我们再次以通常的方式输出这个外部解。\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// 输出我们的计算结果是一个相当机械的任务。这个函数的所有组成部分之前已经讨论过了。\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// 这是最主要的功能。它应该是不言自明的。\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// 这是本程序的主要功能。它与以前所有的教程程序完全一样。\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": "#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 <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 * @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の測定値とオドメトリから車体速度を推定する\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 内部状態をリセットする\n     */\n    void reset(void);\n\n    /**\n     * @brief フィルタに新たな入力を与えて出力を更新する\n     * @param accel 加速度センサーの測定値\n     * @param gyro ジャイロスコープの測定値\n     * @param wheel_velocity 車輪速度\n     * @param wheel_current モーター電流\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 車体速度の推定値を取得する\n     * @return 車体速度 X [m/s], Y [m/s], ω [rad/s]\n     */\n    Eigen::Vector3f bodyVelocity(void) const {\n        return {_mu(0), _mu(1), _mu(2)};\n    }\n\n    /**\n     * @brief 摩擦係数の推定値を取得する\n     * @return 摩擦係数 [Ns]\n     */\n    Eigen::Vector4f frictionCoefficients(void) const {\n        return {_mu(3), _mu(4), _mu(5), _mu(6)};\n    }\n\n    /// 状態変数の最尤値\n    Vector7f _mu;\n\n    /// 共分散\n    Matrix7f _sigma;\n\n    /// 前回の更新時の車輪速度\n    Eigen::Vector4f _last_wheel_velocity;\n\n    /// 線形化された状態方程式\n    Matrix7f G;\n\n    /// 線形化された観測方程式\n    Matrix7f H;\n\n    /// 逆行列を求める際の途中計算結果\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": "/* 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 \"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": "/*! @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// 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": "#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örgs 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 * @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": "#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": "/* \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": "// Copyright © 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": "/******************************************************************************\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": "\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": "// 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": "/* 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̅\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": "/* 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 * 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": "/* 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": "#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": "#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 © 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": "/**\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": "/* 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": "#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": "//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 <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 <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 <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": "///////////////////////////////////////////////////////////////////\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": "/*\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": "#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": "#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 <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": "\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": "// 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// 常见无约束优化算法\n// 直接方法\n// 间接方法\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_;  // 一阶求导矩阵\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 使用秩为2的模拟牛顿法, BFGS\n * @param 求解的问题f\n * @param 初始点 var_x,是一个向量，可包含多维\n * @param 终止条件 delta, 默认 0.001\n * @param 是否打印中间结果\n * @return 求解得到的最优点 \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 单位矩阵\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 使用BFGS的外点法\n * @param 初始点 var_x,是一个向量，可包含多维\n * @param 终止条件 delta, 默认 0.001\n * @param 是否打印中间结果\n * @return 求解得到的最优点 \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": "// 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 Örnhag\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": "#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/*!\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": "#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": "/* \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": "// 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änkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#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": "/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\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": "#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//  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": "\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// 包含文件是  step-40  ,  step-16  , 和  step-37  的组合。\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// 我们使用与 step-40 相同的策略，在PETSc和Trilinos之间进行切换。\n\n#include <deal.II/lac/generic_linear_algebra.h> \n\n// 如果你已经安装了PETSc和Trilinos，并且你喜欢在本例中使用PETSc，请将下面的预处理程序定义注释进去或退出。\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// 以下文件用于组装误差估计器，如  step-12  。\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运算符必须使用 dealii::LinearAlgebra::distributed::Vector 矢量类型。这里我们定义了复制到Trilinos向量的操作，以便与基于矩阵的代码兼容。请注意，目前PETSc矢量类型不存在这种功能，所以必须安装Trilinos来使用本教程中的MatrixFree求解器。\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// 让我们继续描述我们要解决的问题。我们把右边的函数设置为1.0。 @p value 函数返回一个VectorizedArray，被无矩阵代码路径所使用。\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// 接下来的这个类表示扩散系数。我们使用一个可变的系数，在任何一个至少有一个坐标小于-0.5的点上是100.0，在所有其他点上是1.0。如上所述，一个单独的value()返回一个VectorizedArray，用于无矩阵代码。一个 @p average()函数计算了一组点的算术平均。\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// 当在MatrixFree框架中使用一个系数时，我们还需要一个函数，为MatrixFree运算符参数提供的一组单元格创建一个系数表。\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// 我们将使用ParameterHandler来在运行时传入参数。 该结构 @p Settings 解析并存储这些参数，以便在整个程序中进行查询。\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// 这是该程序的主类。它看起来与  step-16  ,  step-37  , 和  step-40  非常相似。对于MatrixFree的设置，我们使用 MatrixFreeOperators::LaplaceOperator 类，它在内部定义了`local_apply()`, `compute_diagonal()`, 和`set_coefficient()`函数。请注意，多项式的度数是这个类的一个模板参数。这对无矩阵代码来说是必要的。\n\ntemplate <int dim, int degree> \nclass LaplaceProblem \n{ \npublic: \n  LaplaceProblem(const Settings &settings); \n  void run(); \n\nprivate: \n\n// 我们将在整个程序中使用以下类型。首先是基于矩阵的类型，之后是无矩阵的类。对于无矩阵的实现，我们使用 @p float 作为水平运算符。\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// 关于构造函数的唯一有趣的部分是，除非我们使用AMG，否则我们会构造多网格的层次结构。为此，我们需要在这个构造函数完成之前解析运行时参数。\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// 与  step-16  和  step-37  不同，我们将设置分成两部分，setup_system() 和 setup_multigrid() 。下面是大多数教程中常见的主动网格的典型setup_system()函数。对于无矩阵，活动网格的设置类似于  step-37  ；对于基于矩阵（GMG和AMG求解器），设置类似于  step-40  。\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// 该函数为无矩阵和基于矩阵的GMG进行多级设置。无矩阵的设置类似于 step-37 ，而基于矩阵的设置类似于 step-16 ，只是我们必须使用适当的分布式稀疏度模式。\n\n// 该函数没有被AMG方法调用，但为了安全起见，该函数的主`switch`语句还是确保了该函数只在已知的多网格设置下运行，如果该函数被调用到两种几何多网格方法以外的地方，则抛出一个断言。\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// 汇编被分成三个部分：`assemble_system()`, `assemble_multigrid()`, 和`assemble_rhs()`。这里的`assemble_system()`函数组装并存储（全局）系统矩阵和基于矩阵的方法的右手边。它类似于  step-40  中的装配。\n\n// 注意，无矩阵方法不执行这个函数，因为它不需要组装矩阵，而是在assemble_rhs()中组装右手边。\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// 下面的函数为基于矩阵的GMG方法组装和存储多级矩阵。这个函数与 step-16 中的函数类似，只是在这里它适用于分布式网格。这个区别在于增加了一个条件，即我们只在本地拥有的水平单元上进行组装，并为每个被建立的矩阵调用压缩（）。\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// 这个三要素中的最后一个函数为无矩阵方法组装右手边的向量--因为在无矩阵框架中，我们不需要组装矩阵，只需要组装右手边就可以了。我们可以通过从上面的`assemble_system()`函数中提取处理右手边的代码来做到这一点，但是我们决定完全采用无矩阵的方法，也用这种方法进行装配。\n\n// 结果是一个类似于 step-37 中 \"使用 FEEvaluation::read_dof_values_plain() 来避免解决约束 \"一节中的函数。\n\n// 这个函数的原因是MatrixFree运算符不考虑非同质的Dirichlet约束，而是将所有的Dirichlet约束视为同质的。为了说明这一点，这里的右手边被组装成残差 $r_0 = f-Au_0$ ，其中 $u_0$ 是一个零向量，除了在Dirichlet值中。然后在求解的时候，我们可以看到，解决方案是  $u = u_0 + A^{-1}r_0$  。这可以看作是对初始猜测为  $u_0$  的线性系统进行的牛顿迭代。下面`solve()`函数中的CG解计算了 $A^{-1}r_0$ ，调用`constraints.distribution()`（直接在后面）增加了 $u_0$  。\n\n// 显然，由于我们考虑的是一个零迪里希特边界的问题，我们可以采取类似于 step-37  `assemble_rhs()`的方法，但是这个额外的工作允许我们改变问题声明，如果我们选择的话。\n\n// 这个函数在积分循环中有两个部分：通过提交梯度的负值将矩阵  $A$  的负值应用于  $u_0$  ，并通过提交值  $f$  添加右手边的贡献。我们必须确保使用`read_dof_values_plain()`来评估 $u_0$ ，因为`read_dof_vaues()`会将所有Dirichlet值设置为0。\n\n// 最后，system_rhs向量的类型是 LA::MPI::Vector, ，但MatrixFree类只对 dealii::LinearAlgebra::distributed::Vector. 起作用，因此我们必须使用MatrixFree功能计算右手边，然后使用`ChangeVectorType`命名空间的函数将其复制到正确的类型。\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// 这里我们设置了多网格预处理程序，测试了单个V型周期的时间，并解决了线性系统。不出所料，这是三种方法差别最大的地方之一。\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// 无矩阵GMG方法的求解器类似于  step-37  ，除了增加一些接口矩阵，完全类似于  step-16  。\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// 将求解向量和右手边从 LA::MPI::Vector 复制到 dealii::LinearAlgebra::distributed::Vector ，这样我们就可以解决了。\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个V型周期的时间安排。\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// 解出线性系统，更新解的鬼魂值，复制回 LA::MPI::Vector 并分配约束。\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// 基于矩阵的GMG方法的求解器，类似于  step-16  ，只是使用了雅可比平滑器，而不是SOR平滑器（该平滑器没有并行实现）。\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个V型周期的计时。\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// 解决线性系统和分配约束。\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方法的求解器，类似于  step-40  。\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个V型周期的计时。\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// 解决线性系统和分配约束。\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// 我们使用FEInterfaceValues类来组装一个误差估计器，以决定哪些单元需要细化。请看介绍中对单元和面积分的确切定义。为了使用该方法，我们为 MeshWorker::mesh_loop() 定义了Scratch和Copy对象，下面的大部分代码本质上与 step-12 中已经设置的一样（或者至少精神上相似）。\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// 剩余单元的汇编程序  $h^2 \\| f + \\epsilon \\triangle u \\|_K^2$  。\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// 脸部术语的汇编器  $\\sum_F h_F \\| \\jump{\\epsilon \\nabla u \\cdot n} \\|_F^2$  。\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// 我们需要对每个内部面进行一次装配，但我们需要确保两个进程都对本地拥有的单元和幽灵单元之间的面术语进行装配。这可以通过设置 MeshWorker::assemble_ghost_faces_both 标志来实现。我们需要这样做，因为我们不在这里交流误差估计器的贡献。\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// 我们使用存储在向量 @p estimate_vector 中的单元估计器，并细化固定数量的单元（这里选择的是每一步中大约两倍的DoFs数量）。\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()函数与许多教程中的函数类似（例如，见 step-40 ）。\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// 和大多数教程一样，这个函数调用上面定义的各种函数来设置、组合、求解和输出结果。\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// 我们只为GMG方法输出层次单元数据（与下面的DoF数据相同）。请注意，对于AMG来说，分区效率是不相关的，因为在计算过程中没有分布或使用层次结构。\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// 只为GMG设置多级层次结构。\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// 对于无矩阵的方法，我们只组装右手边。对于这两种基于矩阵的方法，我们同时装配主动矩阵和右手边，对于基于矩阵的GMG，我们只装配多网格矩阵。\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// 这是一个类似于 step-40 的主函数，但我们要求用户传递一个.prm文件作为唯一的命令行参数（参见 step-29 和ParameterHandler类的文档，以了解关于参数文件的完整讨论）。\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": "/**\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 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": "/// \\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": "//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": "/*\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": "#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": "#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": "//******************************************************************************\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": "//  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 © 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 <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": "// 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": "#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": "#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": "// 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": "////////////////////////////////////////////////////////////////////////////////\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": "//    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": "// 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": "#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": "// 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": "// 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": "#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": "/*********************************************************************\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": "// 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 <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// エラトステネスの篩\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// 素数リスト\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": "/*****************************************************************************/\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": "#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": "#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": "#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": "//\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#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": "#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–Box 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": "//\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": "#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": "// 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] ± 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": "/* -*- 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 <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": "// ----------------------------------------------------------------------------\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": "#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": "//==================================================================================================\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": "/**\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": "// 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": "// 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": "//\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−3iN+6i+3N^2−12N+11)s_{yyy}\n  //     −i/6(i+1)(2i−3N+4)s_{yyx}\n  //     +i/6(i−1)(i+1)s_{yxx}\n  //     −i/6(i^2−3i(N−1)+3N^2−6N+2)s_{xyy}\n  //     +i/6(i−1)(2i−3N+2))s_{xxy}\n  //     −i/6(i^2−3i+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;  // 求解的向量是6＊1的\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> BlockSolverType;  // 求解的向量是6＊1的\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": "#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": "#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": "#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": "#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": "#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": "#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 à 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èle à A1B1 décalée de vOffset\n\t\n\t\tPoint O = vec2Point(B, vOffset*cmpt); // à 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érifie qu'ils ne sont pas colinéaires\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 ça signifie qu'on est arrivé 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êtes\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é 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érifie que nos points sont dans l'approxPoly, s'ils n'y sont pas, on les force à 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 (à 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é 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 (à 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é 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é\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ête à couper, leur ordre spatial ne change pas, et le polygone est codé 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": "// -*- 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": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\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": "#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": "#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": "// 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": "// 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": "//==============================================================================\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": "// ---------------------------------------------------------------------\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 <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": "/* 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": "/* 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": "#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": "/*  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 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": "#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": "\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// 本程序中使用的大部分include文件都是 step-6 和类似程序中众所周知的。\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// 新的只有以下三个。第一个声明了DiscreteTime类，它帮助我们在时间相关的模拟中跟踪时间。后面两个提供了所有的粒子功能，即记录位于网格上的粒子的方法（ Particles::ParticleHandler 类）和为可视化目的输出这些粒子的位置及其属性的能力（ Particles::DataOut  类）。\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// 按照惯例，我们把所有与程序细节相对应的东西都放到一个自己的命名空间中。在顶部，我们定义了一些常量，我们宁愿使用符号名称而不是硬编码的数字。\n\n// 具体来说，我们为几何学的各个部分定义了 @ref GlossBoundaryIndicator \"边界指标 \"的数字，以及电子的物理属性和我们在这里使用的其他具体设置。\n\n// 对于边界指标，让我们从某个随机值101开始列举。这里的原则是要使用*不常见的数字。如果之前有`GridGenerator'函数设置的预定义边界指标，它们很可能是从0开始的小整数，但不是在这个相当随机的范围内。使用下面这样的数字可以避免冲突的可能性，同时也减少了在程序中直接拼出这些数字的诱惑（因为你可能永远不会记得哪个是哪个，而如果它们从0开始，你可能会受到诱惑）。\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// 然后，下面是这个程序的主类。从根本上说，它的结构与 step-6 和其他许多教程程序相同。这包括大部分的成员函数（其余部分的目的可能从它们的名字中不难看出），以及超出 step-6 的少量成员变量，所有这些都与处理粒子有关。\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// 那么，让我们开始执行。构造函数所做的实际上只是对顶部的所有成员变量进行简单的初始化。唯一值得一提的是`particle_handler'，它被交给了一个指向粒子所在的三角形的引用（目前当然还是空的，但是粒子处理程序存储了这个引用，一旦粒子被添加，就会使用它--这发生在三角形被构建之后）。它得到的另一个信息是每个粒子需要存储多少 \"属性\"。在这里，我们需要每个粒子记住的是它当前的速度，也就是一个带有`dim`分量的矢量。然而，每个粒子还有其他的内在属性， Particles::ParticleHandler 类会自动并始终确保这些属性是可用的；特别是，这些属性是粒子的当前位置、它所在的单元格、它在该单元格中的参考位置，以及粒子的ID。\n\n// 唯一感兴趣的其他变量是 \"时间\"，一个DiscreteTime类型的对象。它记录了我们在一个随时间变化的模拟中的当前时间，并以开始时间（零）和结束时间（ $10^{-4}$ ）初始化。我们以后将在`update_timestep_size()`中设置时间步长。\n\n// 构造函数的主体由我们在介绍中已经讨论过的一段代码组成。也就是说，我们要确保每次有粒子离开域时，`track_lost_particle()`函数都会被`particle_handler`对象调用。\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// 下一个函数是负责生成我们要解决的网格。回顾一下域的样子。    \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>  我们把这个几何体细分为 $4\\times 2$ 个单元的网格，看起来像这样。\n//    @code\n//    *---*---*---*---*\n//    \\   |   |   |   |\n//     *--*---*---*---*\n//    /   |   |   |   |\n//    *---*---*---*---*\n//  @endcode \n//  这样做的方法是首先定义 $15=5\\times 3$ 顶点的位置--在这里，我们说它们在整数点上，左边的中间点向右移动了`delta=0.5`的值。\n\n// 在下文中，我们必须说明哪些顶点共同组成了8个单元。下面的代码就完全等同于我们在 step-14 中的做法。\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// 有了这些数组，我们可以转向稍高的高层数据结构。我们创建一个CellData对象的向量，为每个要创建的单元存储相关的顶点以及 @ref GlossMaterialId \"材料ID\"（我们在这里将其简单地设置为0，因为我们在程序中不使用它）。\n\n// 然后，这些信息将被传递给 Triangulation::create_triangulation() 函数，并对网格进行两次全局细化。\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// 该函数的其余部分循环所有的单元格和它们的面，如果一个面在边界上，则决定哪个边界指标应该应用于它。如果你将代码与上面的几何图形相比较，各种条件应该是有意义的。\n\n// 一旦完成了这一步，我们再全局地细化一下网格。\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// 本程序中的下一个函数是处理与解决偏微分方程有关的各种对象的设置。它本质上是对 step-6 中相应函数的复制，不需要进一步讨论。\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// 计算矩阵项的函数实质上还是复制了  step-6  中的相应函数。\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// 这个函数唯一有趣的部分是它是如何形成线性系统的右手边的。回顾一下，PDE的右边是\n// @f[\n//    \\sum_p (N e)\\delta(\\mathbf x-\\mathbf x_p),\n//  @f]\n//  ，在这里我们用 $p$ 来索引粒子，以避免与形状函数 $\\varphi_i$ 混淆； $\\mathbf x_p$ 是第 $p$ 个粒子的位置。\n\n// 当与测试函数 $\\varphi_i$ 相乘并在域上积分时，会得到一个右手边的向量\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//  注意最后一行不再包含一个积分，因此也没有出现 $dx$ ，这需要在我们的代码中出现`JxW`符号。\n// \n// 对于一个给定的单元 $K$ ，这个单元对右边的贡献是\n//  @f{align*}{\n//    F_i^K &= \\sum_{p, \\mathbf x_p\\in K} (N e) \\varphi_i(\\mathbf x_p),\n//  @f}，\n//  也就是说，我们只需要担心那些实际位于当前单元 $K$ 上的粒子。\n\n// 在实践中，我们在这里所做的是以下几点。如果当前单元格上有任何粒子，那么我们首先获得一个迭代器范围，指向该单元格的第一个粒子以及该单元格上最后一个粒子之后的粒子（或结束迭代器）--即C++函数中常见的半开放范围。现在知道了粒子的列表，我们查询它们的参考位置（相对于参考单元），评估这些参考位置的形状函数，并根据上面的公式计算力（没有任何  FEValues::JxW).  ）。\n// @note  值得指出的是，调用 Particles::ParticleHandler::particles_in_cell() 和 Particles::ParticleHandler::n_particles_in_cell() 函数在有大量粒子的问题上不是很有效。但是它说明了写这个算法的最简单的方法，所以我们愿意为了说明问题而暂时承担这个代价。  我们在下面的<a href=\"#extensions\">\"possibilities for extensions\" section</a>中更详细地讨论了这个问题，并在 step-70 中使用了一个更好的方法，例如：。\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// 最后，我们可以把这个单元格的贡献复制到全局矩阵和右边的向量中。\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// 解决线性系统的函数又与 step-6 中的完全一样。\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// 最后一个与场相关的函数是细化网格的函数。我们将在第一个时间步骤中多次调用它，以获得一个能很好地适应解的结构的网格，特别是解决解中由于重心角和边界条件类型变化的地方而产生的各种奇异现象。你可能想再参考一下 step-6 以了解更多的细节。\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// 现在让我们来看看处理粒子的函数。第一个是关于粒子的创建。正如介绍中提到的，如果电场 $\\mathbf E=\\nabla V$ 超过某个阈值，即如果 $|\\mathbf E| \\ge E_\\text{threshold}$ ，并且如果电场进一步指向域内（即如果 $\\mathbf E \\cdot \\mathbf n < 0$ ），我们希望在阴极的各点创建一个粒子。正如有限元方法中常见的那样，我们在特定的评估点评估场（及其导数）；通常，这些是 \"正交点\"，因此我们创建了一个 \"正交公式\"，我们将用它来指定我们要评估解决方案的点。在这里，我们将简单地采用QMidpoint，意味着我们将只在面的中点检查阈值条件。然后我们用它来初始化一个FEFaceValues类型的对象来评估这些点的解。\n\n// 然后，所有这些将被用于所有单元格、它们的面，特别是那些位于边界的面，而且是边界的阴极部分的循环中。\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// 所以我们已经找到了阴极上的一个面。接下来，我们让FEFaceValues对象计算每个 \"正交 \"点的解的梯度，并通过 @ref vector_valued \"矢量值问题 \"文件模块中讨论的方法，以张量变量的形式从梯度中提取电场向量。\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// 只有当电场强度超过阈值时，电子才能逃离阴极，而且关键是，如果电场指向*域内，电子才能逃离阴极。      一旦我们检查了这一点，我们就在这个位置创建一个新的 Particles::Particle 对象，并将其插入到 Particles::ParticleHandler 对象中，并设置一个唯一的ID。            这里唯一不明显的是，我们还将这个粒子与我们当前所在的单元格的参考坐标中的位置联系起来。这样做是因为我们将在下游函数中计算诸如粒子位置的电场等量（例如，在每个时间步长中更新其位置时计算作用于它的力）。在任意坐标上评估有限元场是一个相当昂贵的操作，因为形状函数实际上只定义在参考单元上，所以当要求一个任意点的电场时，我们首先要确定这个点的参考坐标是什么。为了避免反复操作，我们一次性地确定这些坐标，然后将这些参考坐标直接存储在粒子上。\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// 在所有这些插入结束时，我们让`particle_handler`更新它所存储的粒子的一些内部统计数据。\n\n    particle_handler.update_cached_numbers(); \n  } \n// @sect4{CathodeRaySimulator::move_particles}  \n\n// 第二个与粒子有关的函数是在每个时间步骤中移动粒子的函数。要做到这一点，我们必须在所有的单元格、每个单元格中的粒子上循环，并评估每个粒子位置的电场。\n\n// 这里使用的方法在概念上与`assemble_system()`函数中使用的相同。我们在所有单元中循环，找到位于那里的粒子（同样要注意这里用来寻找这些粒子的算法的低效率），并使用FEPointEvaluation对象来评估这些位置的梯度。\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// 然后，我们可以向FEPointEvaluation对象询问这些位置的解决方案的梯度（即电场 $\\mathbf E$ ），并在各个粒子上循环。\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// 现在我们已经得到了其中一个粒子位置的电场，我们首先用它来更新速度，然后更新位置。为此，我们首先从粒子的属性中获取旧的速度，计算加速度，更新速度，并将这个新的速度再次存储在粒子的属性中。回顾一下，这对应于介绍中所讨论的以下一组更新方程中的第一个。      \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// 有了新的速度，我们也就可以更新粒子的位置，并告诉粒子这个位置。\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// 在更新了所有粒子的位置和属性（即速度）之后，我们需要确保`particle_handler`再次知道它们在哪个单元中，以及它们在参考单元坐标系中的位置。下面的函数就是这样做的。(它还确保在并行计算中，如果粒子从一个处理器拥有的子域移动到另一个处理器拥有的子域，那么粒子会从一个处理器移动到另一个处理器。)\n\n    particle_handler.sort_particles_into_subdomains_and_cells(); \n  } \n// @sect4{CathodeRaySimulator::track_lost_particle}  \n\n// 最后一个与粒子相关的函数是当一个粒子从模拟中丢失时被调用的函数。这通常发生在它离开域的时候。如果发生这种情况，这个函数会同时调用单元（我们可以询问它的新位置）和它之前所在的单元。然后，该函数不断跟踪更新这个时间步骤中丢失的粒子数，丢失的粒子总数，然后估计该粒子是否通过阳极中间的孔离开。我们这样做，首先检查它最后所在的单元是否有一个 $x$ 坐标在右边边界的左边（位于 $x=4$ ），而粒子现在的位置在右边边界的右边。如果是这样的话，我们就计算出它的运动方向矢量，这个方向矢量被归一化了，所以方向矢量的 $x$ 分量等于 $1$  。有了这个方向矢量，我们可以计算出它与直线 $x=4$ 的相交位置。如果这个相交点在 $0.5$ 和 $1.5$ 之间，那么我们就声称粒子从孔中离开，并增加一个计数器。\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// 正如在介绍中详细讨论的那样，我们需要尊重一个时间步长条件，即颗粒在一个时间步长中不能移动超过一个单元。为了确保这一点，我们首先计算每个单元上所有粒子的最大速度，然后用该速度除以单元大小。然后，我们使用介绍中讨论的安全系数，将下一个时间步长计算为所有单元上这个量的最小值，并使用 DiscreteTime::set_desired_time_step_size() 函数将其设定为所需的时间步长。\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// 正如在介绍中提到的，我们必须以不同的方式对待第一个时间步长，因为在那里，粒子还没有出现，或者还没有我们计算合理步长所需的相关信息。下面的公式遵循介绍中的讨论。\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// 实现整个算法的最后一个函数是生成图形输出的函数。在目前的情况下，我们想同时输出电势场以及粒子的位置和速度。但我们也想输出电场，即解决方案的梯度。\n\n// deal.II有一个一般的方法，可以从解决方案中计算出派生量，并输出这些量。在这里，这是电场，但也可以是其他的量--比如说，电场的法线，或者事实上任何其他人们想从解 $V_h(\\mathbf x)$ 或其导数中计算的量。这个一般的解决方案使用了DataPostprocessor类，在像这里的情况下，我们想输出一个代表矢量场的量，则使用DataPostprocessorVector类。\n\n// 与其尝试解释这个类是如何工作的，不如让我们简单地参考一下DataPostprocessorVector类的文档，这个案例基本上是一个有据可查的例子。\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// 有了这个，`output_results()`函数就变得相对简单了。我们使用DataOut类，就像我们在以前几乎所有的教程程序中使用的那样，来输出解决方案（\"电动势\"），我们使用上面定义的后处理程序来输出其梯度（\"电场\"）。这些都被写入一个VTU格式的文件中，同时将当前时间和时间步长与该文件联系起来。\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// 输出粒子的位置和属性并不复杂。 Particles::DataOut 类扮演了粒子的DataOut类的角色，我们所要做的就是告诉该类从哪里获取粒子，以及如何解释属性中的`dim`分量--即作为表示速度的单一矢量，而不是作为`dim`标量属性。剩下的就和上面一样了。\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// 这个程序的主类的最后一个成员函数是驱动。在顶层，它通过在一连串越来越细的网格上求解问题（尚未创建粒子），对网格进行多次细化。\n\n  template <int dim> \n  void CathodeRaySimulator<dim>::run() \n  { \n    make_grid(); \n\n//在前面做几个细化循环\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// 现在进行时间上的循环。这个步骤的顺序紧跟介绍中讨论的算法大纲。正如在DiscreteTime类的文档中详细讨论的那样，虽然我们将场和粒子信息向前移动了一个时间步长，但存储在`time`变量中的时间与这些量的（部分）位置不一致（在DiscreteTime的字典中，这就是 \"更新阶段\"）。对`time.advance_time()`的调用通过将`time`变量设置为场和粒子已经处于的时间而使一切重新保持一致，一旦我们处于这个 \"一致阶段\"，我们就可以生成图形输出并将模拟的当前状态的信息写入屏幕。\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// 程序的最后一个函数又是`main()`函数。自 step-6 以来，它在所有的教程程序中都没有变化，因此没有什么新的内容需要讨论。\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": "//---------------------------------------------------------------------------------------------------------------------\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": "// 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 \"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": "#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 <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": "/**\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": "#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": "#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//  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// we 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////                     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": "/* ------------------------------------------------------------------------- */\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 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 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 * 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": "#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": "/*\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": "// 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": "/*\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": "#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": "// 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  Θ  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²\nusing force        = mpl::vector_c<int, 1, 1, -2, 0, 0, 0, 0>; // ML/T²\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 <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": "#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": "#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": "#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": "﻿#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": "#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": "//==================================================================================================\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 * 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": "// 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": "/**\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": "#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": "// ----------------------------------------------------------------------------\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": "#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": "/*\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": "#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": "#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": "/*  _______________________________________________________________________\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": "#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": "// 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": "/**\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": "#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 <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": "/** \\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": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// 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": "// ----------------------------------------------------------------------------\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": "#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": "#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": "﻿#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 ⊆ 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 ⊆ 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": "//\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üero 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": "#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": "/**\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": "\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": "#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": "/* 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": "// 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": "// 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én 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": "// 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–644, 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–644, 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/*!\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": "//\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": "#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 * 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": "//#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": "/*********************************************************************\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": "/* -*- 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–260 (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": "//######################################################################\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// 首先包括deal.II库中的必要文件。\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// 这包括有效实现无矩阵方法的数据结构，或者用MatrixFree类的更通用的有限元算子。\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// 为了提高效率，在无矩阵实现中进行的操作需要在编译时了解循环长度，这些长度是由有限元的度数给出的。因此，我们收集了两个模板参数的值，可以在代码中的一个地方改变。当然，我们可以把有限元的度数作为一个运行时的参数，通过编译所有可能的度数（比如，1到6之间）的计算核，并在运行时选择合适的核。在这里，我们只是选择二阶 $Q_2$ 元素，并选择维度3作为标准。\n\n  const unsigned int degree_finite_element = 2; \n  const unsigned int dimension             = 3; \n// @sect3{Equation data}  \n\n// 我们为泊松问题定义了一个可变系数函数。它与 step-5 中的函数类似，但我们使用 $a(\\mathbf x)=\\frac{1}{0.05 + 2\\|\\bf x\\|^2}$ 的形式，而不是不连续的形式。这只是为了证明这种实现的可能性，而不是在物理上有什么意义。我们定义系数的方式与早期教程程序中的函数相同。有一个新的函数，即有模板参数 @p value 的 @p number. 方法。\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// 这就是上面提到的新函数。评估抽象类型的系数  @p number.  它可能只是一个普通的双数，但也可能是一个有点复杂的类型，我们称之为VectorizedArray。这种数据类型本质上是一个短的双数数组，正如在介绍中所讨论的那样，它可以容纳几个单元格的数据。例如，我们在这里评估的系数不是像通常那样在一个简单的点上，而是交给一个Point<dim,VectorizedArray<double>>点，在AVX的情况下，它实际上是四个点的集合。不要把VectorizedArray中的条目与点的不同坐标混淆。事实上，数据的布局是这样的： <code>p[0]</code> 返回一个VectorizedArray，它又包含了第一个点和第二个点的x坐标。你可以使用例如  <code>p[0][j]</code>  单独访问坐标，j=0,1,2,3，但建议尽可能在一个VectorizedArray上定义操作，以便利用矢量操作。\n\n// 在函数的实现中，我们假设数字类型重载了基本的算术运算，所以我们只需照常写代码。然后，基类函数 @p value 是由带有双倍类型的模板函数计算出来的，以避免重复代码。\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// 下面这个名为 <code>LaplaceOperator</code> 的类，实现了微分运算符。就所有的实用目的而言，它是一个矩阵，也就是说，你可以向它询问它的大小（成员函数  <code>m(), n()</code>  ），你可以将它应用于一个矢量（ <code>vmult()</code>  函数）。当然，与实数矩阵的区别在于，这个类实际上并不存储矩阵的<i>elements</i>，而只知道如何计算运算器应用于向量时的动作。\n\n// 描述矩阵大小的基础结构，来自MatrixFree对象的初始化，以及通过vmult()和Tvmult()方法实现矩阵-向量乘积的各种接口，是由本类派生的 MatrixFreeOperator::Base 类提供的。这里定义的LaplaceOperator类只需要提供几个接口，即通过vmult()函数中使用的apply_add()方法来实现运算符的实际操作，以及计算底层矩阵对角线项的方法。我们需要对角线来定义多梯度平滑器。由于我们考虑的是一个具有可变系数的问题，我们进一步实现了一个可以填充系数值的方法。\n\n// 注意文件 <code>include/deal.II/matrix_free/operators.h</code> 已经包含了通过类 MatrixFreeOperators::LaplaceOperator. 对拉普拉斯的实现。 出于教育目的，本教程程序中重新实现了该运算符，解释了其中的成分和概念。\n\n// 这个程序利用了集成在deal.II中的有限元算子应用的数据缓存。这个数据缓存类被称为MatrixFree。它包含局部和全局自由度之间的映射信息（Jacobian）和索引关系。它还包含约束条件，如来自悬挂节点或迪里切特边界条件的约束。此外，它可以在所有单元上以%并行方式发出一个循环，确保只有不共享任何自由度的单元被处理（这使得循环在写入目标向量时是线程安全的）。与 @ref threads 模块中描述的WorkStream类相比，这是一个更先进的策略。当然，为了不破坏线程安全，我们在写进类全局结构时必须小心。\n\n// 实现拉普拉斯算子的类有三个模板参数，一个是维度（正如许多deal.II类所携带的），一个是有限元的度数（我们需要通过FEEvaluation类来实现高效计算），还有一个是底层标量类型。我们希望对最终矩阵使用 <code>double</code> 数字（即双精度，64位浮点），但对多网格级矩阵使用浮点数（单精度，32位浮点数字）（因为那只是一个预处理程序，而浮点数的处理速度是两倍）。FEEvaluation类也需要一个模板参数，用于确定一维正交点的数量。在下面的代码中，我们把它硬编码为  <code>fe_degree+1</code>  。如果我们想独立于多项式程度来改变它，我们需要添加一个模板参数，就像在  MatrixFreeOperators::LaplaceOperator  类中做的那样。\n\n// 顺便说一下，如果我们在同一个网格和自由度上实现了几个不同的操作（比如质量矩阵和拉普拉斯矩阵），我们将为每个操作者定义两个像现在这样的类（来自于 MatrixFreeOperators::Base 类），并让它们都引用一般问题类中的同一个MatrixFree数据缓存。通过 MatrixFreeOperators::Base 的接口要求我们只提供一组最小的函数。这个概念允许编写具有许多无矩阵操作的复杂应用代码。\n\n//  @note  储存类型 <code>VectorizedArray<number></code> 的值需要注意。在这里，我们使用deal.II表类，它准备以正确的对齐方式保存数据。然而，存储例如一个 <code>std::vector<VectorizedArray<number> ></code> 是不可能用矢量化的。数据与内存地址的边界需要一定的对齐（基本上，在AVX的情况下，一个32字节的VectorizedArray需要从一个能被32整除的内存地址开始）。表类（以及它所基于的AlignedVector类）确保这种对齐方式得到尊重，而 std::vector 一般不这样做，这可能会导致一些系统在奇怪的地方出现分段故障，或者其他系统的性能不理想。\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// 这是 @p LaplaceOperator 类的构造函数。它所做的就是调用基类 MatrixFreeOperators::Base, 的默认构造函数，而基类又是基于Subscriptor类的，它断言这个类在超出范围后不会被访问，比如在一个预处理程序中。\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// 为了初始化系数，我们直接赋予它上面定义的系数类，然后选择带有矢量数的方法 <code>coefficient_function.value</code> （编译器可以从点数据类型中推导出来）。下面将解释FEEvaluation类（及其模板参数）的使用。\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// 这里是这个类的主要功能，矩阵-向量乘积的评估（或者，一般来说，有限元算子评估）。这是在一个函数中完成的，该函数需要四个参数，MatrixFree对象，目标和源向量，以及要处理的单元格范围。MatrixFree类中的方法 <code>cell_loop</code> 将在内部用一些单元格范围来调用这个函数，这些单元格范围是通过检查哪些单元格可以同时工作来获得的，这样写操作就不会引起任何竞赛条件。请注意，循环中使用的单元格范围并不是直接指当前网格中的（活动）单元格数量，而是一个单元格批次的集合。 换句话说，\"单元 \"可能是一个错误的开始，因为FEEvaluation将几个单元的数据分组在一起。这意味着在正交点的循环中，我们实际上是将几个单元的正交点作为一个块来看待。这样做是为了实现更高的矢量化程度。 这种 \"单元 \"或 \"单元批 \"的数量存储在MatrixFree中，可以通过 MatrixFree::n_cell_batches(). 查询。与deal.II单元迭代器相比，在这个类中，所有的单元都被布置在一个普通的数组中，不直接知道水平或相邻关系，这使得通过无符号整数索引单元成为可能。\n\n// 拉普拉斯运算符的实现非常简单。首先，我们需要创建一个对象FEEvaluation，它包含计算核，并有数据字段来存储临时结果（例如，在几个单元格集合的所有正交点上评估的梯度）。请注意，临时结果不会使用大量的内存，而且由于我们用元素顺序指定模板参数，数据被存储在堆栈中（没有昂贵的内存分配）。通常，只需要设置两个模板参数，维度作为第一个参数，有限元的度数作为第二个参数（这等于每个维度的自由度数减去FE_Q元素的一个）。然而，在这里，我们也希望能够使用浮点数来计算多网格预处理，这是最后一个（第五个）模板参数。因此，我们不能依赖默认的模板参数，因此必须填写第三和第四个字段。第三个参数指定每个方向的正交点的数量，其默认值等于元素的度数加1。第四个参数设置分量的数量（在PDEs系统中也可以评估矢量值的函数，但默认是标量元素），最后一个参数设置数字类型。\n\n// 接下来，我们在给定的单元格范围内循环，然后继续进行实际的实现。  <ol>  \n// <li>  告诉FEEvaluation对象我们要处理的（宏）单元。   <li>  读入源向量的值（  @p read_dof_values),  包括约束的解析。这将存储 $u_\\mathrm{cell}$ ，如介绍中所述。   <li>  计算单元格梯度（有限元函数的评价）。由于FEEvaluation可以结合值计算和梯度计算，它使用一个统一的接口来处理0到2阶之间的各种导数。我们只想要梯度，不想要值，也不想要二阶导数，所以我们在梯度槽（第二槽）中将函数参数设置为真，而在值槽（第一槽）中设置为假。还有一个用于Hessian的第三槽，默认为假，所以不需要给它。请注意，FEEvaluation类在内部以一种有效的方式评估形状函数，一次只处理一个维度（如介绍中提到的使用形状函数和正交点的张量积形式）。与FEValues中使用的在所有局部自由度和正交点上循环的天真方法相比，在 $d$ 维度上，这给出了等于 $\\mathcal O(d^2 (p+1)^{d+1})$ 的多项式度数 $p$ 的复杂度，并花费了 $\\mathcal O(d (p+1)^{2d})$  。   <li>  接下来是雅各布变换的应用，乘以变量系数和正交权重。FEEvaluation有一个访问函数 @p get_gradient ，可以应用Jacobian并返回实空间中的梯度。然后，我们只需要乘以（标量）系数，并让函数 @p submit_gradient 应用第二个雅各布式（用于测试函数）和正交权重及雅各布式行列式（JxW）。注意，提交的梯度存储在与 @p get_gradient. 中读取梯度的地方相同的数据字段中。因此，你需要确保在调用 @p submit_gradient 后不要再从同一正交点读取该特定正交点。一般来说，当 @p get_gradient 被多次使用时，复制其结果是个好主意。   <li>  接下来是对所有测试函数的正交点进行求和，对应于实际积分步骤。对于拉普拉斯算子，我们只是乘以梯度，所以我们用各自的参数集调用积分函数。如果你有一个方程，同时用测试函数的值和梯度进行测试，那么两个模板参数都需要设置为真。先调用积分函数的值，再单独调用梯度，会导致错误的结果，因为第二次调用会在内部覆盖第一次调用的结果。请注意，积分步骤的二次导数没有函数参数。   <li>  最终，介绍中提到的向量 $v_\\mathrm{cell}$ 中的局部贡献需要被添加到结果向量中（并应用约束）。这是通过调用 @p distribute_local_to_global, 来完成的，该函数与AffineConstraints中的相应函数名称相同（只是我们现在将局部向量存储在FEEvaluation对象中，正如局部和全局自由度之间的指数一样）。   </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// 这个函数实现了对 Base::apply_add() 接口的所有单元的循环。这是用MatrixFree类的 @p cell_loop 来实现的，它接受这个类的operator()，参数为MatrixFree, OutVector, InVector, cell_range。当使用MPI并行化（但没有线程）时，如本教程程序中所做的，单元格循环对应于以下三行代码。\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// 这里，两个调用update_ghost_values()和compress()为MPI执行处理器边界上的数据交换，一次用于源向量，我们需要从远程处理器拥有的条目中读取，一次用于目的向量，我们已经积累了部分残余，需要添加到所有者处理器的相应条目中。然而， MatrixFree::cell_loop 不仅抽象出这两个调用，而且还进行了一些额外的优化。一方面，它将把update_ghost_values()和compress()的调用拆开，以允许通信和计算的重叠。然后用三个代表从0到 MatrixFree::n_cell_batches(). 的单元格范围的分区来调用local_apply函数。另一方面，cell_loop也支持线程并行，在这种情况下，单元格范围被分割成更小的块，并以一种先进的方式安排，避免了几个线程对同一个向量条目的访问。这一特性在  step-48  中有解释。\n\n// 注意，在单元格循环之后，受约束的自由度需要再次被触及，以实现合理的vmult()操作。由于装配循环会自动解决约束问题（就像 AffineConstraints::distribute_local_to_global() 的调用一样），它不会计算对受约束自由度的任何贡献，而是将各自的条目留为零。这将表示一个矩阵的受限自由度的行和列都是空的。然而，像CG这样的迭代求解器只对非星形矩阵有效。最简单的方法是将矩阵中对应于受限自由度的子块设置为同一矩阵，在这种情况下，矩阵的应用只是将右侧向量的元素复制到左侧。幸运的是，vmult()的实现 MatrixFreeOperators::Base 在apply_add()函数之外自动为我们做了这个，所以我们不需要在这里采取进一步的行动。\n\n// 当使用MatrixFree和FEEvaluation的组合与MPI并行时，有一个方面需要注意&mdash; 用于访问向量的索引。出于性能的考虑，MatrixFree和FEEvaluation被设计为在MPI本地索引空间中访问向量，当与多个处理器一起工作时也是如此。在本地索引空间工作意味着除了不可避免的间接寻址外，在向量访问发生的地方不需要进行索引转换。然而，本地索引空间是模糊的：虽然标准的惯例是用0和本地大小之间的索引访问向量的本地拥有的范围，但对于重影项的编号并不那么明确，而且有些随意。对于矩阵-向量乘积，只有出现在本地拥有的单元格上的指数（加上那些通过悬挂节点约束引用的指数）是必要的。然而，在deal.II中，我们经常将重影元素上的所有自由度设置为重影向量条目，称为 @ref GlossLocallyRelevantDof \"术语表中描述的本地相关DoF\"。在这种情况下，尽管指的是同一个全局索引，但在两个可能的重影集中，重影向量条目的MPI本地索引一般会有所不同。为了避免问题，FEEvaluation通过一个名为 LinearAlgebra::distributed::Vector::partitioners_are_compatible. 的检查来检查用于矩阵-向量乘积的向量分区是否确实与MatrixFree中的索引分区相匹配。 为了方便， MatrixFreeOperators::Base 类包括一个机制来使鬼魂集适合正确的布局。这发生在向量的重影区域，所以请记住，在调用vmult()方法后，目标和源向量的重影区域都可能被修改。这是合法的，因为分布式deal.II向量的ghost区域是一个可变的部分，并按需填充。在矩阵-向量乘积中使用的向量在进入vmult()函数时不能被重影，所以没有信息丢失。\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// 下面的函数实现了算子对角线的计算。计算无矩阵算子评估的矩阵项，结果比评估算子更复杂。从根本上说，我们可以通过在<i>all</i>单位向量上应用算子来获得算子的矩阵表示。当然，这将是非常低效的，因为我们需要进行<i>n</i>运算符的评估来检索整个矩阵。此外，这种方法会完全忽视矩阵的稀疏性。然而，对于单个单元来说，这是一种方法，而且实际上效率并不低，因为单元内的所有自由度之间通常都存在着耦合。\n\n// 我们首先将对角线向量初始化为正确的平行布局。这个向量被封装在基类 MatrixFreeOperators::Base. 中DiagonalMatrix类型的一个名为inverse_diagonal_entries的成员中，这个成员是一个共享指针，我们首先需要初始化它，然后获得代表矩阵中对角线条目的向量。至于实际的对角线计算，我们再次使用MatrixFree的cell_loop基础设施来调用一个名为local_compute_diagonal()的本地工作程序。由于我们只写进一个向量，而没有任何源向量，我们用一个<tt>unsigned int</tt>类型的假参数来代替源向量，以便与cell_loop接口确认。在循环之后，我们需要将受Dirichlet边界条件约束的向量条目设置为1（要么是MatrixFree内部AffineConstraints对象描述的边界上的条目，要么是自适应多网格中不同网格层次之间的索引）。这是通过函数 MatrixFreeOperators::Base::set_constrained_entries_to_one() 完成的，并与Base算子提供的矩阵-向量乘积中的设置相匹配。最后，我们需要反转对角线条目，这是基于Jacobi迭代的Chebyshev平滑器所要求的形式。在循环中，我们断言所有的条目都是非零的，因为它们应该从积分中获得正的贡献，或者被约束并被 @p set_constrained_entries_to_one() 以下的cell_loop处理。\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// 在本地计算循环中，我们通过循环本地矩阵中的所有列来计算对角线，并将条目1放在<i>i</i>槽中，将条目0放在所有其他槽中，也就是说，我们一次在一个单位向量上应用单元格微分运算。调用 FEEvaluation::evaluate, 的内部部分是对正交点的循环， FEEvalution::integrate, 则与local_apply函数完全相同。之后，我们挑出本地结果的第<i>i</i>个条目，并将其放入一个临时存储器（因为我们在下一次循环迭代时覆盖了 FEEvaluation::get_dof_value() 后面数组中的所有条目）。最后，临时存储被写到目标向量中。注意我们是如何使用 FEEvaluation::get_dof_value() 和 FEEvaluation::submit_dof_value() 来读取和写入FEEvaluation用于积分的数据字段，并在另一方面写入全局向量的。\n\n// 鉴于我们只对矩阵的对角线感兴趣，我们简单地扔掉了沿途计算过的本地矩阵的所有其他条目。虽然计算完整的单元格矩阵，然后扔掉除对角线以外的所有东西看起来很浪费，但是整合的效率很高，所以计算并没有花费太多时间。请注意，对于多项式度数来说，每个元素的算子评估的复杂度是 $\\mathcal O((p+1)^{d+1})$ ，所以计算整个矩阵要花费我们 $\\mathcal O((p+1)^{2d+1})$ 次操作，与用FEValues计算对角线的复杂度 $\\mathcal O((p+1)^{2d})$ 相差不大。由于FEEvaluation也由于矢量化和其他优化而大大加快了速度，所以用这个函数计算对角线实际上是最快的（简单的）变量。(有可能用 $\\mathcal O((p+1)^{d+1})$ 操作中的和分解技术来计算对角线，这涉及到特别适应的内核&mdash;但是由于这种内核只在特定的环境下有用，而对角线计算通常不在关键路径上，所以它们没有在deal.II中实现。)\n\n// 注意在向量上调用distribution_local_to_global来将对角线条目累积到全局矩阵的代码有一些限制。对于带有悬空节点约束的操作者来说，在distribution_local_to_global的调用中，将一个受约束的DoF的积分贡献分配给其他几个条目，这里使用的向量接口并不完全计算对角线条目，而是将一些位于本地矩阵对角线上的贡献，最终在全局矩阵的非对角线位置堆积到对角线上。如<a href=\"http:dx.doi.org/10.4208/cicp.101214.021015a\">Kormann (2016), section 5.3</a>中所解释的，该结果在离散化精度上是正确的，但在数学上并不平等。在这个教程程序中，不会发生任何危害，因为对角线只用于没有悬空节点约束出现的多网格水平矩阵中。\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// 这个类是基于  step-16  中的一个。然而，我们用我们的无矩阵实现取代了SparseMatrix<double>类，这意味着我们也可以跳过稀疏性模式。请注意，我们定义LaplaceOperator类时，将有限元的度数作为模板参数（该值在文件的顶部定义），我们使用浮点数来表示多网格级矩阵。\n\n// 该类还有一个成员变量，用来记录在我们真正去解决这个问题之前设置整个数据链的所有详细时间。此外，还有一个输出流（默认情况下是禁用的），可以用来输出各个设置操作的细节，而不是默认情况下只打印出的摘要。\n\n// 由于这个程序被设计成与MPI一起使用，我们也提供了通常的 @p pcout 输出流，只打印MPI等级为0的处理器的信息。这个程序使用的网格可以是基于p4est的分布式三角图（在deal.II被配置为使用p4est的情况下），否则它就是一个只在没有MPI的情况下运行的串行网格。\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// 当我们初始化有限元时，我们当然也要使用文件顶部指定的度数（否则，在某些时候会抛出一个异常，因为在模板化的LaplaceOperator类中定义的计算内核和MatrixFree读出的有限元信息将不匹配）。三角形的构造函数需要设置一个额外的标志，告诉网格要符合顶点上的2:1单元平衡，这对于几何多网格例程的收敛是必需的。对于分布式网格，我们还需要特别启用多网格的层次结构。\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类拥有一个额外的输出流，用于收集关于设置阶段的详细时间信息。这个流被称为time_details，默认情况下通过这里指定的 @p false 参数被禁用。对于详细的时间，去掉 @p false 参数可以打印出所有的细节。\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// 设置阶段与 step-16 类似，由于LaplaceOperator类的存在而有相关的变化。首先要做的是设置DoFHandler，包括多网格层次的自由度，以及初始化悬挂节点的约束和同质二列条件。由于我们打算用MPI的%并行方式使用这个程序，我们需要确保约束条件能知道本地相关的自由度，否则在使用超过几亿个自由度的时候，存储会爆炸，见  step-40  。\n\n// 一旦我们创建了多网格dof_handler和约束条件，我们就可以为全局矩阵算子以及多网格方案的每一层调用reinit函数。主要的操作是为问题设置 <code> MatrixFree </code> 实例。 <code>LaplaceOperator</code> 类的基类， MatrixFreeOperators::Base, 被初始化为一个指向MatrixFree对象的共享指针。这样，我们可以在这里简单地创建它，然后将它分别传递给系统矩阵和水平矩阵。为了设置MatrixFree，我们需要激活MatrixFree的AdditionalData字段中的更新标志，使其能够存储实空间中的正交点坐标（默认情况下，它只缓存梯度（反转置的雅各布）和JxW值的数据）。请注意，如果我们调用 reinit 函数而不指定级别（即给出  <code>level = numbers::invalid_unsigned_int</code>  ），MatrixFree 将在活动单元上构建一个循环。在本教程中，除了MPI之外，我们不使用线程，这就是为什么我们通过将 MatrixFree::AdditionalData::tasks_parallel_scheme 设置为 MatrixFree::AdditionalData::none. 来明确地禁用它 最后，系数被评估，向量被初始化，如上所述。\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// 接下来，初始化所有层次上的多网格方法的矩阵。数据结构MGConstrainedDoFs保留了受边界条件约束的指数信息，以及不同细化层次之间的边缘指数，如 step-16 教程程序中所述。然后，我们穿过网格的各个层次，在每个层次上构建约束和矩阵。这与原始网格上的系统矩阵的构造密切相关，只是在访问层级信息而不是活动单元的信息时，在命名上略有不同。\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// 组装函数非常简单，因为我们所要做的就是组装右侧。多亏了FEEvaluation和所有缓存在MatrixFree类中的数据，我们从 MatrixFreeOperators::Base, 中查询，这可以在几行中完成。由于这个调用没有被包裹到 MatrixFree::cell_loop 中（这将是一个替代方案），我们一定不要忘记在装配结束时调用compress()，将右手边的所有贡献发送给各自自由度的所有者。\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// 解决的过程与  step-16  中类似。我们先从转移的设置开始。对于 LinearAlgebra::distributed::Vector, 来说，有一个非常快速的转移类，叫做MGTransferMatrixFree，它用FEEvaluation中同样的快速和因子化核在网格层之间进行插值。\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// 作为一个平滑器，本教程程序使用切比雪夫迭代，而不是 step-16 中的SOR。（SOR将很难实现，因为我们没有明确的矩阵元素，而且很难使其在%并行中有效工作）。 平滑器是用我们的水平矩阵和切比雪夫平滑器的强制性附加数据初始化的。我们在这里使用一个相对较高的度数（5），因为矩阵-向量乘积是比较便宜的。我们选择在平滑器中平滑出 $[1.2 \\hat{\\lambda}_{\\max}/15,1.2 \\hat{\\lambda}_{\\max}]$ 的范围，其中 $\\hat{\\lambda}_{\\max}$ 是对最大特征值的估计（系数1.2在PreconditionChebyshev中应用）。为了计算该特征值，Chebyshev初始化执行了几步没有预处理的CG算法。由于最高的特征值通常是最容易找到的，而且一个粗略的估计就足够了，我们选择10次迭代。最后，我们还设置了切比雪夫方法中的内部预处理类型，这是一个雅可比迭代。这由DiagonalMatrix类来表示，该类得到了由我们的LaplaceOperator类提供的反对角线条目。\n\n// 在第0层，我们以不同的方式初始化平滑器，因为我们想使用切比雪夫迭代作为求解器。PreconditionChebyshev允许用户切换到求解器模式，其中迭代次数在内部选择为正确值。在附加数据对象中，通过将多项式的度数选择为 @p numbers::invalid_unsigned_int. 来激活这一设置，然后算法将攻击粗级矩阵中最小和最大之间的所有特征值。切比雪夫平滑器的步数是这样选择的：切比雪夫收敛估计值保证将残差减少到变量 @p  smoothing_range中指定的数字。注意，对于求解来说， @p smoothing_range 是一个相对的公差，并且选择小于1，在这种情况下，我们选择三个数量级，而当只对选定的特征值进行平滑时，它是一个大于1的数字。\n\n// 从计算的角度来看，只要粗粒度适中，Chebyshev迭代是一个非常有吸引力的粗粒度求解器。这是因为Chebyshev方法只执行矩阵-向量乘积和向量更新，这通常比其他迭代方法中涉及的内积更好地并行到有几万个核心的最大集群规模。前者只涉及到（粗）网格中邻居之间的局部通信，而后者则需要在所有处理器上进行全局通信。\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// 下一步是设置悬挂节点情况下所需的接口矩阵。deal.II中的自适应多网格实现了一种叫做局部平滑的方法。这意味着最细级别的平滑只覆盖固定（最细）网格级别所定义的网格的局部部分，而忽略了计算域中终端单元比该级别更粗的部分。随着该方法向更粗的级别发展，越来越多的全局网格将被覆盖。在某个更粗的层次上，整个网格将被覆盖。由于多网格方法中的所有层次矩阵都覆盖了网格中的单一层次，所以在层次矩阵上不会出现悬空节点。在多网格层之间的界面上，在平滑的同时设置同质Dirichlet边界条件。然而，当残差被转移到下一个更粗的层次时，需要考虑到多网格界面的耦合。这是由所谓的界面（或边缘）矩阵来完成的，它计算了被具有同质Dirichlet条件的层次矩阵所遗漏的残差部分。我们参考 @ref mg_paper \"Janssen和Kanschat的多网格论文 \"以了解更多细节。\n\n// 对于这些接口矩阵的实现，已经有一个预定义的类 MatrixFreeOperators::MGInterfaceOperator ，它将例程 MatrixFreeOperators::Base::vmult_interface_down() 和 MatrixFreeOperators::Base::vmult_interface_up() 包装在一个带有 @p vmult()和 @p Tvmult() 操作（最初是为矩阵编写的，因此期待这些名字）的新类中。请注意，vmult_interface_down是在多网格V周期的限制阶段使用的，而vmult_interface_up是在延长阶段使用的。\n\n// 一旦接口矩阵被创建，我们完全按照 step-16 的方法设置剩余的多网格预处理基础设施，以获得一个可以应用于矩阵的 @p preconditioner 对象。\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// 多网格程序的设置非常简单，与  step-16  相比，在求解过程中看不出有什么不同。所有的魔法都隐藏在  LaplaceOperator::vmult  操作的实现背后。请注意，我们通过标准输出打印出求解时间和累积的设置时间，也就是说，在任何情况下，而设置操作的详细时间只在构造函数中的detail_times标志被改变的情况下打印。\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// 这里是数据输出，是  step-5  的简化版本。我们对细化过程中产生的每个网格使用标准的VTU（=压缩的VTK）输出。此外，我们还使用了一种针对速度而不是磁盘使用量进行优化的压缩算法。默认设置（针对磁盘使用进行优化）使得保存输出的时间是运行线性求解器的4倍，而将 DataOutBase::VtkFlags::compression_level 设置为 DataOutBase::VtkFlags::best_speed 则将其降低到只有线性求解的四分之一的时间。\n\n// 当网格过大时，我们禁用输出。这个程序的一个变种已经在几十万个MPI行列上运行，网格单元多达1000亿个，经典的可视化工具无法直接访问。\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// 运行该程序的函数与  step-16  中的函数非常相似。与2D相比，我们在3D中做了很少的细化步骤，但仅此而已。\n\n// 在运行程序之前，我们先输出一些关于检测到的矢量化水平的信息，正如在介绍中所讨论的那样。\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// 除了我们根据 step-40 设置了MPI框架外，主函数中没有任何意外。\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": "/*\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 <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": "#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モデルのモード出力用　@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ステップの最適化問題を解き，最適入力u0を求める\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// 全時刻のuをu0で埋める\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)）\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（Eq.(7)）\n\t\tmodel->phix(taut, xtau.elem(dv), ltau.elem(dv));\n\n\t\t// Calculate costate sequence by recursive backward difference calculation（Eq.(6)）\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（Eq.(5)）\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 //前進差分計算のためにxの時間微分xdが必要だが，実際の計算ではxdを求めないため，ここで差分で近似している\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//// もし更新したutauでのhutauが更新前より悪化した場合は戻す\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": "\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// 就像以前的例子一样，我们必须包括几个文件，其中的含义已经讨论过了。\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// 下面两个文件提供了多线程程序的类和信息。在第一个文件中，声明了我们需要做并行装配的类和函数（即\n// <code>WorkStream</code>\n// 命名空间）。第二个文件有一个类MultithreadInfo，可以用来查询系统中的处理器数量，这在决定启动多少个并行线程时通常很有用。\n\n#include <deal.II/base/work_stream.h>\n#include <deal.II/base/multithread_info.h>\n\n// 下一个新的include文件声明了一个基类 <code>TensorFunction</code> ，与\n// <code>Function</code> 类不一样，但不同的是 TensorFunction::value\n// 返回一个张量而不是一个标量。\n\n#include <deal.II/base/tensor_function.h>\n\n#include <deal.II/numerics/error_estimator.h>\n\n// 这是C++，因为我们想把一些输出写入磁盘。\n\n#include <fstream>\n#include <iostream>\n\n// 最后一步和以前的程序一样。\n\nnamespace Step9\n{\n  using namespace dealii;\n  // @sect3{Equation data declaration}\n\n  // 接下来我们声明一个描述平流场的类。当然，这是一个矢量场，有多少分量就有多少空间维度。现在我们可以使用一个从\n  // <code>Function</code>\n  // 基类派生出来的类，就像我们在前面的例子中对边界值和系数所做的那样，但是在库中还有另一种可能性，即一个描述张量值函数的基类。这比重写\n  // Function::value()\n  // 知道多个函数成分的方法更方便：最后我们需要一个张量，所以我们不妨直接使用一个返回张量的类。\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    // 在前面的例子中，我们已经在多个地方使用了抛出异常的断言。但是，我们还没有看到如何声明这种异常。这可以这样做。\n\n    DeclException2(ExcDimensionMismatch,\n                   unsigned int,\n                   unsigned int,\n                   << \"The vector has size \" << arg1 << \" but should have \"\n                   << arg2 << \" elements.\");\n\n    // 语法可能看起来有点奇怪，但很合理。其格式基本如下：使用其中一个宏的名称\n    // <code>DeclExceptionN</code>, where <code>N</code>\n    // 表示异常对象应采取的附加参数的数量。在本例中，由于我们想在两个向量的大小不同时抛出异常，我们需要两个参数，所以我们使用\n    // <code>DeclException2</code>\n    // 。第一个参数描述了异常的名称，而下面的参数则声明了参数的数据类型。最后一个参数是一连串的输出指令，这些指令将被输送到\n    // <code>std::cerr</code>  对象中，因此出现了奇怪的格式，前面是\n    // <code>@<@<</code>  操作符之类的。注意，我们可以通过使用名称\n    // <code>arg1</code> through <code>argN</code>  来访问在构造时（即在\n    // <code>Assert</code>  调用中）传递给异常的参数，其中  <code>N</code>\n    // 是通过使用各自的宏  <code>DeclExceptionN</code>  来定义的参数数。\n\n    // 要了解预处理器如何将这个宏扩展为实际代码，请参考异常类的文档。简而言之，这个宏调用声明并定义了一个继承自\n    // ExceptionBase 的类  <code>ExcDimensionMismatch</code>\n    // ，它实现了所有必要的错误输出功能。\n  };\n\n  // 下面的两个函数实现了上述的接口。第一个简单地实现了介绍中所描述的函数，而第二个使用了同样的技巧来避免调用虚拟函数，在前面的例子程序中已经介绍过了。注意第二个函数中对参数的正确大小的检查，这种检查应该始终存在于这类函数中；根据我们的经验，许多甚至大多数编程错误都是由不正确的初始化数组、不兼容的函数参数等造成的；像本例中那样使用断言可以消除许多这样的问题。\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  // 除了平流场，我们还需要两个描述源项（  <code>right hand side</code>\n  // ）和边界值的函数。如介绍中所述，源是一个源点附近的常数函数，我们用常数静态变量\n  // <code>center_point</code>  表示。我们使用与我们在 step-7\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  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  // 这里唯一的新东西是我们检查 <code>component</code>\n  // 参数的值。由于这是一个标量函数，很明显，只有当所需分量的索引为0时才有意义，所以我们断言这确实是这样的。\n  // <code>ExcIndexRange</code>\n  // 是一个全局预定义的异常（可能是最经常使用的异常，因此我们让它成为全局的，而不是某个类的局部），它需要三个参数：超出允许范围的索引，有效范围的第一个元素和超过最后一个的元素（即又是C++标准库中经常使用的半开放区间）。\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  // 最后是边界值，这只是从 <code>Function</code> 基类派生的另一个类。\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  // 这里是这个程序的主类。它和前面的例子中的主类非常相似，所以我们再次只对其不同之处进行评论。\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    // 下一组函数将被用来组装矩阵。然而，与前面的例子不同，\n    // <code>assemble_system()</code>\n    // 函数不会自己做这些工作，而是将实际的装配工作委托给辅助函数\n    // <code>assemble_local_system()</code>  和\n    // <code>copy_local_to_global()</code>\n    // 。其原理是，矩阵组装可以很好地并行化，因为每个单元的局部贡献的计算完全独立于其他单元，我们只需要在将一个单元的贡献添加到全局矩阵中时进行同步。\n\n    // 我们在这里选择的并行化策略是文档中 @ref threads 模块中详细提及的可能性之一。具体来说，我们将使用那里讨论的WorkStream方法。由于这个模块有很多文档，我们不会在这里重复设计选择的理由（例如，如果你读完上面提到的模块，你会明白 <code>AssemblyScratchData</code> 和 <code>AssemblyCopyData</code> 结构的目的是什么）。相反，我们将只讨论具体的实现。\n\n    // 如果你阅读了上面提到的页面，你会发现为了使汇编并行化，我们需要两个数据结构--一个对应于我们在局部集成过程中需要的数据（\"scratch\n    // data\"，即我们只需要作为临时存储的东西），另一个是将信息从局部集成携带到函数中，然后将局部贡献添加到全局矩阵的相应元素中。其中前者通常包含FEValues和FEFaceValues对象，而后者则有局部矩阵、局部右手边，以及关于哪些自由度生活在我们正在组装局部贡献的单元上的信息。有了这些信息，下面的内容应该是相对不言自明的。\n\n    struct AssemblyScratchData\n    {\n      AssemblyScratchData(const FiniteElement<dim> &fe);\n      AssemblyScratchData(const AssemblyScratchData &scratch_data);\n\n      // FEValues和FEFaceValues是很昂贵的设置对象，所以我们把它们包含在scratch对象中，以便尽可能多的数据在单元格之间被重复使用。\n\n      FEValues<dim>     fe_values;\n      FEFaceValues<dim> fe_face_values;\n\n      // 我们还存储了一些向量，我们将在每个单元格上填充数值。在通常情况下，设置这些对象是很便宜的；但是，它们需要内存分配，这在多线程应用程序中可能很昂贵。因此，我们把它们保存在这里，这样在一个单元格上的计算就不需要新的分配。\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      // 最后，我们需要描述该问题数据的对象。\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    // 下面的函数又和前面的例子一样，后面的变量也是一样的。\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  // 现在，最后，这里有一个类，它将计算每个单元上梯度的差分近似值，并以网格大小的幂数进行权衡，如介绍中所述。这个类是库中\n  // <code>DerivativeApproximation</code>\n  // 类的一个简单版本，它使用类似的技术来获得有限元场的梯度的有限差分近似值，或者更高导数。\n\n  // 该类有一个公共静态函数 <code>estimate</code>\n  // ，被调用来计算误差指标的向量，还有一些私有函数，在所有活动单元上做实际工作。在库的其他部分，我们遵循一个非正式的惯例，使用浮点数向量作为误差指标，而不是常见的双数向量，因为对于估计值来说，额外的精度是没有必要的。\n\n  // 除了这两个函数，该类还声明了两个异常，当一个单元在每个空间方向上都没有邻居时（在这种情况下，介绍中描述的矩阵将是奇异的，不能被倒置），而另一个异常用于更常见的函数参数无效的情况，即一个大小错误的向量。\n\n  // 还有两点意见：首先，这个类没有非静态成员函数或变量，所以这不是一个真正的类，而是起到了C++中\n  // <code>namespace</code>\n  // 的作用。我们选择类而不是命名空间的原因是，这种方式我们可以声明私有的函数。如果在命名空间的头文件中声明一些函数，并在实现文件中实现这些函数和其他函数，这也可以用命名空间来实现。没有在头文件中声明的函数仍然在名字空间中，但不能从外部调用。然而，由于我们这里只有一个文件，在目前的情况下不可能隐藏函数。\n\n  // 第二个意见是，维度模板参数被附在函数上，而不是附在类本身。这样，你就不必像其他大多数情况下那样自己指定模板参数，而是编译器可以从作为第一个参数传递的DoFHandler对象的尺寸中自行计算出其值。\n\n  // 在开始实施之前，让我们也来评论一下并行化策略。我们已经在上面这个程序的主类的声明中介绍了使用WorkStream概念的必要框架。我们将在这里再次使用它。在目前的情况下，这意味着我们必须定义\n  // <ol>  。\n  // <li> 类，用于抓取和复制对象， </li>  。\n  // <li>  一个在一个单元上进行局部计算的函数，以及 </li>\n  // <li>  一个将本地结果复制到全局对象的函数。 </li>\n  // </ol>\n  // 鉴于这个总体框架，我们将稍微偏离它。特别是，WorkStream一般是为这样的情况而发明的，即每个单元上的局部计算<i>adds</i>到一个全局对象--例如，在组装线性系统时，我们将局部贡献添加到全局矩阵和右手边中。WorkStream的设计是为了处理多个线程试图同时进行这种添加的潜在冲突，因此必须提供一些方法来确保每次只有一个线程可以做这个。然而，这里的情况略有不同：我们单独计算每个单元的贡献，但随后我们需要做的是将它们放入每个单元独有的输出向量中的一个元素。因此，不存在来自两个单元的写操作可能发生冲突的风险，也没有必要使用WorkStream的复杂机制来避免冲突的写操作。因此，我们要做的就是这样。我们仍然需要一个持有例如\n  // FEValues 对象的 scratch\n  // 对象。但是，我们只创建一个假的、空的拷贝数据结构。同样，我们确实需要计算本地贡献的函数，但由于它已经可以把结果放到最终位置，我们不需要一个从本地到全球的拷贝函数，而是给\n  // WorkStream::run() 函数一个空函数对象--相当于一个NULL函数指针。\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  // 现在是主类的实现。构造器、析构器和函数 <code>setup_system</code>\n  // 遵循之前使用的模式，所以我们不需要对这三个函数进行评论。\n\n  template <int dim>\n  AdvectionProblem<dim>::AdvectionProblem() /* 第一步，类构造函数 */\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  // 在下面的函数中，矩阵和右手被组装起来。正如上面main类的文档所述，它本身并不做这个，而是委托给接下来的函数，利用 @ref threads 中讨论的WorkStream概念。\n\n  // 如果你看了 @ref threads 模块，你会发现并行装配并不需要大量的额外代码，只要你认真地描述什么是从头开始和复制数据对象，如果你为本地装配和从本地贡献到全局对象的复制操作定义了合适的函数。完成这些工作后，下面将完成所有繁重的工作，使这些操作在多个线程上完成，只要你的系统有多少个内核。\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  // 正如上面已经提到的，我们需要有抓取对象来进行局部贡献的并行计算。这些对象包含FEValues和FEFaceValues对象（以及一些数组），因此我们需要有构造函数和复制构造函数，以便我们能够创建它们。对于单元项，我们需要形状函数的值和梯度、正交点以确定给定点的源密度和平流场，以及正交点的权重乘以这些点的雅各布系数的行列式。相反，对于边界积分，我们不需要梯度，而是需要单元的法向量。这决定了我们必须将哪些更新标志传递给类的成员的构造函数。\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  // 现在，这就是做实际工作的函数。它与前面例子程序中的\n  // <code>assemble_system</code>\n  // 函数没有什么不同，所以我们将再次只对其不同之处进行评论。数学上的东西紧跟我们在介绍中所说的。\n\n  // 不过，这里有一些值得一提的地方。首先，我们把FEValues和FEFaceValues对象移到了ScratchData对象中。我们这样做是因为我们每次进入这个函数时都要简单地创建一个，也就是在每个单元格上。现在发现，FEValues类的编写目标很明确，就是将所有从单元格到单元格保持不变的东西都移到对象的构造中，每当我们移到一个新单元格时，只在\n  // FEValues::reinit()\n  // 做尽可能少的工作。这意味着在这个函数中创建一个这样的新对象是非常昂贵的，因为我们必须为每一个单元格都这样做--这正是我们想通过FEValues类来避免的事情。相反，我们所做的是在抓取对象中只创建一次（或少数几次），然后尽可能多地重复使用它。\n\n  // 这就引出了一个问题：我们在这个函数中创建的其他对象，与它的使用相比，其创建成本很高。事实上，在函数的顶部，我们声明了各种各样的对象。\n  // <code>AdvectionField</code>  ,  <code>RightHandSide</code> and\n  // <code>BoundaryValues</code>\n  // 的创建成本并不高，所以这里没有什么危害。然而，在创建\n  // <code>rhs_values</code>\n  // 和下面类似的变量时，分配内存通常要花费大量的时间，而只是访问我们存储在其中的（临时）值。因此，这些将是移入\n  // <code>AssemblyScratchData</code> 类的候选者。我们将把这作为一个练习。\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    // 我们定义一些缩写，以避免不必要的长行。\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    // 我们声明单元格矩阵和单元格右侧...\n\n    copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n    copy_data.cell_rhs.reinit(dofs_per_cell);\n\n    // ...一个数组，用于保存我们目前正在处理的单元格的自由度的全局索引...\n\n    copy_data.local_dof_indices.resize(dofs_per_cell);\n\n    // ...然后初始化 <code>FEValues</code> 对象...\n\n    scratch_data.fe_values.reinit(cell);\n\n    // ... 获得正交点的右手边和平流方向的数值...\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    // ... 设置流线扩散参数的值，如介绍中所述...\n\n    const double delta = 0.1 * cell->diameter();\n\n    // ...... 并按照上面的讨论，集合对系统矩阵和右手边的局部贡献。\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          // 别名AssemblyScratchData对象，以防止行数过长。\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    // 除了我们现在建立的单元项，本问题的双线性形式还包含域的边界上的项。因此，我们必须检查这个单元的任何一个面是否在域的边界上，如果是的话，也要把这个面的贡献集合起来。当然，双线性形式只包含来自边界\n    // <code>inflow</code>\n    // 部分的贡献，但要找出本单元的某个面是否属于流入边界的一部分，我们必须有关于正交点的确切位置和该点的流动方向的信息；我们使用FEFaceValues对象获得这些信息，并只在主循环中决定某个正交点是否在流入边界上。\n\n    for (const auto &face : cell->face_iterators())\n      if (face->at_boundary())\n        {\n          // 好的，当前单元格的这个面是在域的边界上。就像我们在前面的例子和上面的例子中使用的通常的FEValues对象一样，我们必须重新初始化当前面的FEFaceValues对象。\n\n          scratch_data.fe_face_values.reinit(cell, face);\n\n          // 对于手头的正交点，我们要求提供流入函数的值和流动方向。\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          // 现在循环所有正交点，看看这个面是在边界的流入还是流出部分。法向量指向单元外：由于该面处于边界，法向量指向域外，所以如果平流方向指向域内，其与法向量的标量乘积一定是负的（要知道为什么会这样，请考虑使用余弦的标量乘积定义）。\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              // 如果该面是流入边界的一部分，则使用从FEFaceValues对象中获得的值和介绍中讨论的公式，计算该面对全局矩阵和右侧的贡献。\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    // 复制程序需要的最后一条信息是这个单元上自由度的全局索引，所以我们最后把它们写到本地数组中。\n\n    cell->get_dof_indices(copy_data.local_dof_indices);\n  }\n\n  // 我们需要写的第二个函数是将前一个函数计算出的本地贡献（并放入AssemblyCopyData对象）复制到全局矩阵和右侧向量对象。这基本上就是我们在每个单元上装配东西时，一直作为最后一块代码的内容。因此，下面的内容应该是很明显的。\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  // 这里是线性求解程序。由于系统不再像以前的例子那样是对称正定的，我们不能再使用共轭梯度法。相反，我们使用一个更通用的，不依赖矩阵的任何特殊属性的求解器：GMRES方法。GMRES和共轭梯度法一样，需要一个合适的预处理程序：我们在这里使用一个雅可比预处理程序，它对这个问题来说足够好。\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  // 下面的函数根据介绍中描述的数量来细化网格。各自的计算是在类\n  // <code>GradientEstimation</code>  中进行的。\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  // 这个函数与第6步中的函数类似，但由于我们使用的是高阶有限元，所以我们以不同的方式保存解决方案。像VisIt和Paraview这样的可视化程序通常只能理解与节点相关的数据：它们不能绘制五度基函数，这导致我们计算的解的图片非常不准确。为了解决这个问题，我们为每个单元保存了多个\n  // <em> 补丁 </em> ：在二维中，我们为每个单元在VTU文件中保存64个双线性\n  // \"单元\"，在三维中，我们保存512个。最终的结果是，可视化程序将使用立方体基础函数的片状线性插值：这捕捉到了解决方案的细节，并且在大多数屏幕分辨率下，看起来很平滑。我们在一个单独的步骤中保存网格，没有额外的补丁，这样我们就有了细胞面的视觉表现。\n\n  // 9.1版本的deal.II获得了编写更高程度多项式（即为我们的片状二项式解决方案编写片状二项式可视化数据）VTK和VTU输出的能力：然而，并非所有最新版本的ParaView和Viscit（截至2018年）都能读取这种格式，所以我们在这里使用更古老、更通用（但效率较低）的方法。\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输出可能很昂贵，无论是计算还是写入磁盘。这里我们要求ZLib，一个压缩库，以最大限度地提高吞吐量的方式来压缩数据。\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  // ... 如同主循环（设置-求解-细化）一样，除了循环次数和初始网格之外。\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  // 现在是 <code>GradientEstimation</code> 类的实现。让我们先为\n  // <code>estimate_cell()</code> 函数所使用的 <code>EstimateScratchData</code>\n  // 类定义构造函数。\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    // 我们分配一个向量来保存一个单元的所有活动邻居的迭代器。我们保留活动邻居的最大数量，以避免以后的重新分配。注意这个最大的活动邻居数是如何计算出来的。\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  // 接下来是对 <code>GradientEstimation</code>\n  // 类的实现。第一个函数除了将工作委托给另一个函数外，并没有做什么，但在顶部有一点设置。\n\n  // 在开始工作之前，我们要检查写入结果的向量是否有正确的大小。在编程中，忘记在调用处正确确定参数大小的错误是很常见的。因为没有发现这种错误所造成的损失往往是微妙的（例如，内存中某个地方的数据损坏，或者是无法重现的结果），所以非常值得努力去检查这些东西。\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  // 这里是通过计算梯度的有限差分近似值来估计局部误差的函数。该函数首先计算当前单元的活动邻居列表，然后为每个邻居计算介绍中描述的数量。之所以有这样的顺序，是因为在局部细化网格的情况下，要找到一个给定的邻居并不是一蹴而就的事情。原则上，一个优化的实现可以在一个步骤中找到邻域和取决于它们的量，而不是先建立一个邻域列表，然后在第二步中找到它们的贡献，但是我们很乐意将此作为一个练习。正如之前所讨论的，传递给 WorkStream::run 的工作者函数是在保留所有临时对象的 \"scratch \"对象上工作。这样，我们就不需要在每次为给定单元调用工作的函数内创建和初始化那些昂贵的对象了。这样的参数被作为第二个参数传递。第三个参数是一个 \"copy-data \"对象（更多信息见 @ref threads ），但我们在这里实际上没有使用这些对象。由于 WorkStream::run() 坚持传递三个参数，我们声明这个函数有三个参数，但简单地忽略了最后一个参数。\n\n  // （从美学角度看，这是不令人满意的。它可以通过使用一个匿名（lambda）函数来避免。如果你允许的话，让我们在这里展示一下如何做。首先，假设我们已经声明这个函数只接受两个参数，省略了未使用的最后一个参数。现在，\n  // WorkStream::run 仍然想用三个参数来调用这个函数，所以我们需要找到一种方法来\n  // \"忘记 \"调用中的第三个参数。简单地像上面那样把指针传给 WorkStream::run\n  // 这个函数是做不到的--编译器会抱怨一个声明为有两个参数的函数在调用时有三个参数。然而，我们可以通过将以下内容作为第三个参数传递给\n  // WorkStream::run(): 来做到这一点\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  //  这并不比下面实现的解决方案好多少：要么例程本身必须带三个参数，要么它必须被带三个参数的东西包起来。我们不使用这种方法，因为在开始时添加未使用的参数更简单。\n\n  // 现在来看看细节。\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    // 我们需要为张量 <code>Y</code> 提供空间，它是Y向量的外积之和。\n\n    Tensor<2, dim> Y;\n\n    // 首先初始化  <code>FEValues</code>  对象，以及  <code>Y</code>  张量。\n\n    scratch_data.fe_midpoint_value.reinit(cell);\n\n    // 现在，在我们继续之前，我们首先计算当前单元的所有活动邻居的列表。我们首先在所有面上进行循环，看那里的邻居是否处于活动状态，如果它与本单元在同一级别或更粗一级，就会出现这种情况（注意，一个邻居只能比本单元粗一次，因为我们在deal.II中只允许在一个面上有一个最大的细化差）。另外，邻居也可能在同一级别，并被进一步细化；那么我们必须找到它的哪些子单元与当前单元相邻，并选择这些子单元（注意，如果一个活动单元的邻居的一个子单元与这个活动单元相邻，那么它本身就必须是活动的，这是由于上面提到的一个细化规则）。\n\n    // 在一个空间维度上，情况略有不同，因为在那里不存在单一细化规则：相邻的活动单元可以在任意多的细化级别上有所不同。在这种情况下，计算变得有点困难，但我们将在下面解释。\n\n    // 在开始对当前单元的所有邻域进行循环之前，我们当然要清除存储活动邻域的迭代器的数组。\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          // 首先定义面的迭代器和邻居的缩写\n\n          const auto face     = cell->face(face_n);\n          const auto neighbor = cell->neighbor(face_n);\n\n          // 然后检查邻居是否是活动的。如果是，那么它就在同一层或更粗的一层（如果我们不是在1D中），而且我们在任何情况下都会对它感兴趣。\n\n          if (neighbor->is_active())\n            scratch_data.active_neighbors.push_back(neighbor);\n          else\n            {\n              // 如果邻居没有活动，则检查其子女。\n\n              if (dim == 1)\n                {\n                  // 要找到与本单元相邻的子单元，如果我们在本单元的左边（n==0），则依次去找其右边的子单元，如果我们在右边（n==1），则依次去找左边的子单元，直到找到一个活动单元。\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                  // 由于这使用了一些非微妙的几何直觉，我们可能想检查一下我们是否做对了，也就是说，检查我们找到的单元格的邻居是否确实是我们目前正在处理的单元。像这样的检查通常是有用的，并且经常发现像上面这一行的算法（不由自主地交换\n                  // <code>n==1</code> for <code>n==0</code>\n                  // 或类似的算法是很简单的）和库中的错误（上面的算法所依据的假设可能是错误的，记录错误，或者由于库中的错误而被违反）。原则上，我们可以在程序运行一段时间后删除这样的检查，但是无论如何留下它来检查库中或上述算法中的变化可能是一件好事。\n                  // 请注意，如果这个检查失败了，那么这肯定是一个无法恢复的错误，而且很可能被称为内部错误。因此我们在这里使用一个预定义的异常类来抛出。\n\n                  Assert(neighbor_child->neighbor(face_n == 0 ? 1 : 0) == cell,\n                         ExcInternalError());\n\n                  // 如果检查成功，我们就把刚刚发现的活动邻居推到我们保留的堆栈中。\n\n                  scratch_data.active_neighbors.push_back(neighbor_child);\n                }\n              else\n\n                // 如果我们不在1d中，我们收集所有 \"在\n                // \"当前面的子面后面的邻居孩子，然后继续前进。\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    // 好了，现在我们有了所有的邻居，让我们开始对他们每个人进行计算。首先，我们做一些预备工作：找出当前单元格的中心和该点的解决方案。后者是以正交点的函数值向量的形式得到的，当然，正交点只有一个。同样地，中心的位置是实空间中第一个（也是唯一的）正交点的位置。\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    // 现在在所有活动邻居上循环，收集我们需要的数据。\n\n    Tensor<1, dim> projected_gradient;\n    for (const auto &neighbor : scratch_data.active_neighbors)\n      {\n        // 然后得到邻近单元的中心和该点的有限元函数值。注意，为了获得这些信息，我们必须重新初始化相邻单元的\n        // <code>FEValues</code> 对象。\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        // 计算连接两个单元格中心的向量 <code>y</code>\n        // 。注意，与介绍不同，我们用 <code>y</code>\n        // 表示归一化的差分向量，因为这是在计算中随处可见的数量。\n\n        Tensor<1, dim> y        = neighbor_center - this_center;\n        const double   distance = y.norm();\n        y /= distance;\n\n        // 然后把这个单元格对Y矩阵的贡献加起来...\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        // ...并更新差额商数之和。\n\n        projected_gradient += (scratch_data.neighbor_midpoint_value[0] -\n                               scratch_data.cell_midpoint_value[0]) /\n                              distance * y;\n      }\n\n    // 如果现在，在收集了来自邻居的所有信息后，我们可以确定当前单元的梯度的近似值，那么我们需要经过跨越整个空间的向量\n    // <code>y</code>\n    // ，否则我们就不会有梯度的所有成分。这可以通过矩阵的可逆性来说明。\n\n    // 如果矩阵不可逆，那么当前单元的活动邻居数量不足。与之前所有的情况（我们提出了异常）相比，这不是一个编程错误：这是一个运行时错误，即使在调试模式下运行良好，也可能在优化模式下发生，所以在优化模式下尝试捕捉这个错误是合理的。对于这种情况，有一个\n    // <code>AssertThrow</code> 宏：它像 <code>Assert</code>\n    // 宏一样检查条件，但不仅仅是在调试模式下；然后输出一个错误信息，但不是像\n    // <code>Assert</code> 宏那样中止程序，而是使用C++的 <code>throw</code>\n    // 命令抛出异常。这样，人们就有可能捕捉到这个错误，并采取合理的应对措施。其中一个措施是在全局范围内细化网格，因为如果初始网格的每个单元都至少被细化过一次，就不会出现方向不足的情况。\n\n    AssertThrow(determinant(Y) != 0, ExcInsufficientDirections());\n\n    // 如果另一方面，矩阵是可反转的，那么就反转它，用它乘以其他数量，然后用这个数量和正确的网格宽度的幂来计算估计误差。\n\n    const Tensor<2, dim> Y_inverse = invert(Y);\n\n    const Tensor<1, dim> gradient = Y_inverse * projected_gradient;\n\n    // 这个函数的最后一部分是将我们刚刚计算出来的内容写入输出向量的元素中。这个向量的地址已经存储在Scratch数据对象中，我们所要做的就是知道如何在这个向量中获得正确的元素--但我们可以问一下我们所在的单元格是第多少个活动单元。\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> 函数与前面的例子类似。主要区别是我们使用MultithreadInfo来设置最大的线程数（更多信息请参见文档模块  @ref threads  \"多处理器访问共享内存的并行计算\"）。使用的线程数是环境变量DEAL_II_NUM_THREADS和  <code>set_thread_limit</code>  的参数的最小值。如果没有给  <code>set_thread_limit</code>  的值，则使用英特尔线程构建块（TBB）库的默认值。如果省略了对  <code>set_thread_limit</code>  的调用，线程的数量将由 TBB 选择，与 DEAL_II_NUM_THREADS无关。\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–Ford 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–Ford algorithm: an edge from u to v, having length\n  // w(u,v), is given the new length w(u,v) + h(u) − 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–Ford 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–Ford algorithm: an edge from u to v, having length\n  // w(u,v), is given the new length w(u,v) + h(u) − 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 <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": "// 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": "// 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": "\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": "#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 (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": "/*\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": "#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 \"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/// \\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 \"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": "\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": "#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": "/* Copyright © 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": "#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 * 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": "#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": "/*\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+ɣ*Δ\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¹([0,T], H¹(Ω))\";\n}\n\ntemplate <int dim>\nstd::string H1H1<dim>::unique_id() const {\n  return \"H¹([0,T], H¹(Ω)) with ɣ=\" + std::to_string(gamma_) + \", α=\" + 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": "#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 <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 <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": "/* -*- 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*\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": "/*\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 <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": "\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": "#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)ロボットのローカル座標での足配置位置\n    double y_;                  //(m)ロボットのローカル座標での足配置位置\n    bool support_foot_is_right; //支持脚がどちらか\n};\n\n/**\n * @brief capture pointによる歩行パターン生成方法\n *\n */\nvoid footStepPlannerCapturePoint()\n{\n    double x = 0, y = 0, xinit = 0, yinit = 0;     //(m) CoMのワールド座標 {CoM = Center of Mass}\n    double xd = 0, yd = 0, xdinit = 0, ydinit = 0; // CoMの速度 v(m/s) xdot(t)\n    double px = 0.0, py = 0.0;                     //(m)　着地位置のワールド座標 これは実用的にはローカルの方が良いのでは？？\n    constexpr double Tc = std::sqrt(zh / g);       //微分方程式の時定数\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        //決められた次の一歩を着く地点までの遊脚の移動を行っている時のシミュレーション---------------\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; //次のCPまでの時間\n            // x = (xinit - px) * C + Tc * xdinit * S + px; // x,xdともにn歩目開始時の状態\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; //ここでのcp_targetは1ループ前の話。\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の軌道(x)\n            cp_y_now = ewt * cp_y_old + (1.0 - ewt) * py; // CPの軌道(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        //次の一歩の目標位置を計算------------------\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; //次の一歩の最初のCPの位置\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": "#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 * @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": "/**\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": "#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–Orcutt 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": "/*********************************************************************\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": "/* 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": "// 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": "//==================================================================================================\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": "#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": "#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 (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": "#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×f2 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 – 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": "// 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": "#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": "/*\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": "// 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": "#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": "/*  \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’s bound for the roots of a polynomial\n        double rho_c = 1 + monicCoeffs.tail(order).cwiseAbs().maxCoeff();\n\n        // Calculate Kojima’s 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": "﻿#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// 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": "/**\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": "#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": "#pragma once\n\n#include \"deom.hpp\"\n#include \"algebra.hpp\"\n#include <Eigen/Eigenvalues>\n#include <experimental/random>\n\n// syl： 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": "/*\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": "#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// 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}}
